在Swift 2.0中将字符转换为Int [英] Convert Character to Int in Swift 2.0
问题描述
我只想将字符转换为 Int 。
这应该很简单。但我还没有发现以前的答案有帮助。总是有一些错误。也许是因为我在Swift 2.0中尝试它。
for i in(unsolved.characters){
fileLines + = String(i).toInt $ b print(i)
}
在Swift 2.0中, toInt()
等已被替换为初始化器。 (在这种情况下, Int(someString)
。)
因为不是所有的字符串都可以转换为int ( Int?
),而不只是一个<$ c $ c> Int 。最好的办法是使用如果let
解开这个可选项。
但是这个代码在Swift 2中工作,并且完成我想要做的事情:
let unsolved =123abc
pre>
var fileLines = [Int]()
for un in unsolved.characters {
let someString = String(i)
if let someInt = Int(someString){
fileLines + = [someInt]
}
print(i)
}
或者,对于Swiftier解决方案:
let unsolved = 123abc
let fileLines = unsolved.characters.filter({Int(String($ 0))!= nil})map({Int(String($ 0))!})
// fileLines = [1,2,3]
与
flatMap
:let fileLines = unsolved.characters.flatMap {Int (String($ 0))}
flatMap
返回数组
包含映射transform
的非nil结果self
...所以当Int(String($ 0))
是nil
时, / p>I just want to convert a character into an Int.
This should be simple. But I haven't found the previous answers helpful. There is always some error. Perhaps it is because I'm trying it in Swift 2.0.
for i in (unsolved.characters) { fileLines += String(i).toInt() print(i) }
解决方案In Swift 2.0,
toInt()
, etc., have been replaced with initializers. (In this case,Int(someString)
.)Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (
Int?
) instead of just anInt
. The best thing to do is unwrap this optional usingif let
.I'm not sure exactly what you're going for, but this code works in Swift 2, and accomplishes what I think you're trying to do:
let unsolved = "123abc" var fileLines = [Int]() for i in unsolved.characters { let someString = String(i) if let someInt = Int(someString) { fileLines += [someInt] } print(i) }
Or, for a Swiftier solution:
let unsolved = "123abc" let fileLines = unsolved.characters.filter({ Int(String($0)) != nil }).map({ Int(String($0))! }) // fileLines = [1, 2, 3]
You can shorten this more with
flatMap
:let fileLines = unsolved.characters.flatMap { Int(String($0)) }
flatMap
returns "anArray
containing the non-nil results of mappingtransform
overself
"… so whenInt(String($0))
isnil
, the result is discarded.这篇关于在Swift 2.0中将字符转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!