从Swift中的Array中选择随机数据

时间:2017-03-30 04:58:37

标签: arrays swift dictionary random

我想创建一个从该列表中提取的3个随机值的新数组,以便在其他两个视图控制器中使用。不确定如何分配数组以便可以访问这些值。

class WorkoutDataSource {
var allWorkouts:[Workout]

init() {
    allWorkouts = []
    let bh1 = Workout(title: "Figure 8s - Clockwise", workoutText: "Clockwise around each leg.", color:  UIColor.flatNavyBlueColorDark())
    allWorkouts.append(bh1)
    let bh2 = Workout(title: "Figure 8s - Counter Clockwise", workoutText: "Counter Clockwise around each leg.", color:  UIColor.flatNavyBlue())
    allWorkouts.append(bh2)
    let bh3 = Workout(title: "Dribble Left Handed", workoutText: "Low and Powerfull.", color:  UIColor.flatTealColorDark())
    allWorkouts.append(bh3)
    let bh4 = Workout(title: "Dribble Right Handed", workoutText: "Low and powerfull", color:  UIColor.flatTeal())
    allWorkouts.append(bh4)
    let bh5 = Workout(title: "Around Both Feet", workoutText: "With feet together, circles around ankles-waist-head, work up & down, the full length of body.", color:  UIColor.flatSkyBlueColorDark())
    allWorkouts.append(bh5)
    let bh6 = Workout(title: "Spider Dribble", workoutText: "feet apart, 1 dribble with each hand in front, then 1 dribble with each hand in back. ", color:  UIColor.flatSkyBlue())
    allWorkouts.append(bh6)
    let bh7 = Workout(title: "Helicopter", workoutText: "1 hand in front, 1 hand in back – move your hands from front to back while catching the ball between your legs.", color:  UIColor.flatGreenColorDark())
    allWorkouts.append(bh7)
    let bh8 = Workout(title: "Scissors - Legs Not Moving", workoutText: "One leg forward and one leg back. Dribble between your legs low and fast.", color:  UIColor.flatGreen())
    allWorkouts.append(bh8)
    let bh9 = Workout(title: "Behind the Back", workoutText: ".",color:  UIColor.flatGray())
    allWorkouts.append(bh9)
    let bh10 = Workout(title: "Fingertip Squeeze", workoutText: ".",color:  UIColor.flatPink())
    allWorkouts.append(bh10)
}


func getWorkOuts() -> [Workout]{

return allWorkouts
}

}

谢谢

1 个答案:

答案 0 :(得分:1)

如果您只想从var workouts = [Workout]() for i in 0 ..< 3 { let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count))) let workout = allWorkouts[ndx] workouts.append(workout) } 数组中获取随机值,那么您可以执行以下操作:

workouts

如果你想随机进行三次训练,并且你不在乎它们是否是唯一的,那么你可以这样做:

Set

var workouts = Set<Workout>() while workouts.count < 3 { let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count))) let workout = allWorkouts[ndx] workouts.insert(workout) } 数组将在那时进行三次训练。

如果您希望随机项目是唯一的,那么您应该使用{{1}}而不是数组,并确保您运行直到获得三个项目,如下所示:

{{1}}