Arrays 在Swift3中的字符串数组中选择一个列表

Arrays 在Swift3中的字符串数组中选择一个列表,arrays,swift,string,random,Arrays,Swift,String,Random,我有个问题。我的数组从列表中随机选取一个字符串,我该怎么做呢 我想从列表中随机挑选一种产品 我的想法是,我可以使用数组再次执行此操作,但我得到以下错误: EXC_BAD_指令(代码=EXC_i386_INVOP,子代码=0x0 我的代码是: private func randomProduct() -> Int { let myArray1 = ["Nintendo Classic Mini NES", "Microsoft Office 2016 Home and Business",

我有个问题。我的数组从列表中随机选取一个字符串,我该怎么做呢

我想从列表中随机挑选一种产品

我的想法是,我可以使用数组再次执行此操作,但我得到以下错误:

EXC_BAD_指令(代码=EXC_i386_INVOP,子代码=0x0

我的代码是:

private func randomProduct() -> Int {
let myArray1 = ["Nintendo Classic Mini NES", "Microsoft Office 2016 Home and Business", "Rubie's Deluxe Muscle Chest Batman Child", "Giro Dime", "Varta Powersports AGM 12V 12Ah 512014010A514", "Pohl-Boskamp Gelomyrtol Forte", "Panasonic ES-LV9N-S803", "Traxxas X-Maxx (77076-4)", "GoPro HERO 4", "Bose Lifestyle 650", "WMF Function 4 Kochtopf-Set 4-teilig", "Microsoft Surface Book", "Hewlett-Packard HP Color LaserJet Pro M252dw (B4A22A)", "Apple iPhone 7", "X-lite X-403GT Elegance", "Denon AVR-X3300W", "Hasbro Spiel des Lebens Banking", "Avent SCD 630/26", "Ray-Ban Aviator Metal RB3025"]
return Int(myArray1[Int(arc4random_uniform(UInt32(myArray1.count)))])!
希望你能帮助我


Thx太多了!

您很接近了,但是您希望使用随机数Int作为索引来查找数组中的字符串。然后返回字符串。因此,只需做一些更改:

private func randomProduct() -> String { // Return String, not Int
    let myArray1 = ["Nintendo Classic Mini NES", "Microsoft Office 2016 Home and Business", "Rubie's Deluxe Muscle Chest Batman Child", "Giro Dime", "Varta Powersports AGM 12V 12Ah 512014010A514", "Pohl-Boskamp Gelomyrtol Forte", "Panasonic ES-LV9N-S803", "Traxxas X-Maxx (77076-4)", "GoPro HERO 4", "Bose Lifestyle 650", "WMF Function 4 Kochtopf-Set 4-teilig", "Microsoft Surface Book", "Hewlett-Packard HP Color LaserJet Pro M252dw (B4A22A)", "Apple iPhone 7", "X-lite X-403GT Elegance", "Denon AVR-X3300W", "Hasbro Spiel des Lebens Banking", "Avent SCD 630/26", "Ray-Ban Aviator Metal RB3025"]
    return myArray1[Int(arc4random_uniform(UInt32(myArray1.count)))] // Remove the Int()
}

数组中的所有字符串都不能转换为
Int
…要添加到这一点,您可能需要返回一个
字符串
,并去掉
返回
行中的
Int