简体   繁体   English

在Swift中使用arc4random_uniform从数组中提取随机字符串

[英]Pulling random string from array with arc4random_uniform in Swift

When I run the app, I keep getting the error: 运行应用程序时,我不断收到错误消息:

"Could not cast value of type 'Swift._NSContiguousString' to 'NSArray'." 

I've tried casting to a String as well, but that obviously wasn't the solution either. 我也尝试过强制转换为String ,但这显然也不是解决方案。 Has anyone encounter this? 有人遇到过吗? I'm just trying to pull a random string from the array. 我只是想从数组中提取随机字符串。

firstArray = ["firstItem", "secondItem", "thirdItem"]
randomArray = firstArray[Int(arc4random_uniform(UInt32(firstArray.count)))] as! NSArray

Thanks 谢谢

Keep your array defined as the following : 保持数组定义如下:

var firstArray = ["firstItem", "secondItem", "thirdItem"]

Then do the random number from here : 然后从这里做随机数:

 let randomIndex = Int(arc4random_uniform(UInt32(firstArray.count)))

Get the result like this : 得到这样的结果:

var result = self.firstArray[randomIndex]

Good luck ! 祝好运 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM