2017-02-17 25 views
-1

我有一個問題。我該怎麼做,我的數組從列表中隨機挑選一個字符串?在Swift3中選擇一個字符串數組中的一個列表

我想從列表中隨機挑選這些產品之一?

我的想法是,我可以用一個數組再這樣做,但我得到這個錯誤:

EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP, subcode=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很多!

+3

您的數組中的字符串都不是轉換爲'Int' ... – Hamish

+0

要補充的,你可能要返回'String',並擺脫'return'行中的'Int'。 – BallpointBen

回答

0

您已經接近,但您希望使用隨機數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() 
} 
相關問題