【问题标题】:Pick one of a list in a String Array in Swift3 [duplicate]在Swift3的字符串数组中选择一个列表[重复]
【发布时间】:2017-02-17 21:49:21
【问题描述】:

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

我想随机选择列表中的这些产品之一?

我的想法是,我可以用数组再做一次,但我得到了这个错误:

EXC_BAD_INSTRUCTION(代码=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)))])!

希望你能帮助我!

非常感谢!

【问题讨论】:

  • 数组中的所有字符串都不能转换为Int...
  • 除此之外,您可能希望返回一个String,并去掉return 行中的Int。

标签: arrays swift string random


【解决方案1】:

你已经接近了,但你想使用随机数 Int 作为索引来在数组中找到你的 String。然后你返回字符串。因此,只需进行一些更改:

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()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2020-11-12
    • 2021-05-27
    • 2014-03-10
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多