Why do I get the error "Argument type 'String' does not conform to expected type 'sequence'

笑着哭i 提交于 2019-12-01 09:50:36

问题


I'm trying to convert user input from a textField to an array. I followed the code that was offered here https://stackoverflow.com/a/27501398

let someString : String = someTextField.text!
let someArray = Array(someString).map { String($0).toInt()! }

But then I get this error:

 Argument type "String" does not conform to expected type "Sequence"

What am I doing wrong?


回答1:


It seems that as of Swift 2.0, String no longer conforms to SequenceType. You can work around this if you're really in love with functional programming. However, there's no need to get so fancy here:

let text : String = "12345"
var digits = [Int]()
for element in text.characters {
    digits.append(Int(String(element))!)
}



回答2:


Swift 4 characters is deprecated, so above code would be like this:

let text : String = "12345"
var digits = [Int]()
for element in text {
    digits.append(Int(String(element))!)
}


来源:https://stackoverflow.com/questions/40639151/why-do-i-get-the-error-argument-type-string-does-not-conform-to-expected-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!