我试图产生一个随机的锻炼'随机数量的练习。
每个练习需要有一个名字(来自一个数组)和一些代表(一个随机数,最终会有'上下限制,具体取决于它的运动类型(例如对于俯卧撑来说只有10个,但是对于“500米行”只有1个。但是这可以在以后出现!现在,我试图找出如何生成随机数量的类实例(I&# 39;然后通过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
如果我完全走错了路,请随时告诉我,但我想我离这儿不远(希望......)
答案 0 :(得分:2)
可能有很多不同的(有效的)方法。其中一个可能是这样的:
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)
输出的内容如下:
[运动(名称:"弓步",代表:8),运动(名称:"跳跃 jacks",reps:6),练习(姓名:"弓步",代表:4), 运动(名称:"深蹲",代表:9),运动(名称:"跳跃 jacks",reps:5),运动(姓名:"深蹲",代表:9)]
注意:您还可以修改(randomInt
)辅助函数以考虑lowerBound我猜