[英]Create random number of class instances - Swift
我正在嘗試通過隨機練習生成一個隨機的“鍛煉”。
每個練習都需要有一個名稱(來自數組)和多個代表(一個隨機數,最終取決於練習的類型而具有“上限和下限”(例如,俯卧撐最多10個,但僅限於此) 1代表“ 500m行”,但是稍后可能會出現!現在,我正在嘗試找出如何生成隨機數量的類實例的方法(然后我將通過segue傳遞這些實例並將其放入tableView中,假設那是可能)
這是我的代碼,目前僅在操場上:
import UIKit
let exerciseArray = ["squats", "pushups", "lunges", "jumping jacks"]
class exerciseInWorkout {
var exerciseName : String
var exerciseReps : Int
init(name: String, reps: Int) {
exerciseName = name
exerciseReps = reps
}
}
let randomkey = Int(arc4random_uniform(4))
let numberOfExercisesInWorkout = Int(arc4random_uniform(10))
// Manually creating a new object of exerciseInWorkout with a random exercise and a random number of reps
let exerciseOne = exerciseInWorkout(name:exerciseArray[randomkey], reps:Int(arc4random_uniform((30))))
//print result to make sure it works
print(exerciseOne.exerciseName, exerciseOne.exerciseReps)
//Have some function here which creates a number of class instances based on the "numberOfExercisesInWorkout" constant
如果我完全走錯了路,請隨時告訴我,但我認為我離我們並不遙遠(希望...)
可能有很多不同的(有效)方法。 其中之一可能是這樣的:
let exerciseArray = ["squats", "pushups", "lunges", "jumping jacks"]
struct Exercise {
let name: String
let reps: Int
}
func randomInt(upperBound: UInt32) -> Int {
return Int(arc4random_uniform(upperBound))
}
let numberOfExercisesInWorkout = randomInt(upperBound: 10)
let exercises: [Exercise] = (1...numberOfExercisesInWorkout).map { _ in
let randomKey = randomInt(upperBound: UInt32(exerciseArray.count))
return Exercise(name: exerciseArray[randomKey], reps: randomInt(upperBound: 10))
}
print(exercises)
輸出如下內容:
[運動(名稱:“ lunges”,次數:8),運動(名稱:“ jumping jacks”,次數:6),運動(名稱:“ lunges”,次數:4),運動(名稱:“ squats”,次數:9),運動(名稱:“ jumping jacks”,次數:5),運動(名稱:“ squats”,次數:9)]
注意 :您也可以修改( randomInt
)輔助函數以考慮我想的lowerBound。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.