我有String
,例如, "7,8,9,10"
,我想转换成的Int
元素的数组即[Int]
将[Int?]转换为[Int]
然而,我的代码目前给我一个[Int?]
代替(可选整数数组)。下面是代码:
let years = (item["years"] as! String)
.componentsSeparatedByString(",")
.map { word in Int(word) }
我尝试了一些东西,比如改变Int(word)
到Int(word!)
,并加入到!
的String)
结束,但SWIFT不喜欢这些想法的样子。
我认为有一些明显的我作为初学者做错了,但我不太确定是什么!任何帮助将不胜感激 - 谢谢!
你是正确的使用flatMap,但你可以这样简化:'let years =(item [“years”] as!) .componentsSeparatedByString(“,”) 。 flatMap {Int($ 0)}' – ebluehands
准确,@ebluehands,谢谢!请指教 –
,需要导入Foundation(componentsSeparatedByString)。对于'纯粹'斯威夫特看到我的答案 – user3441734