問(wèn)題描述
我只想將 character 轉(zhuǎn)換為 Int.
I just want to convert a character into an Int.
這應(yīng)該很簡(jiǎn)單.但我還沒(méi)有發(fā)現(xiàn)以前的答案有幫助.總是有一些錯(cuò)誤.也許是因?yàn)槲艺?Swift 2.0 中嘗試它.
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)
}
推薦答案
在 Swift 2.0 中,toInt()
等已被替換為初始化器.(在這種情況下,Int(someString)
.)
In Swift 2.0, toInt()
, etc., have been replaced with initializers. (In this case, Int(someString)
.)
因?yàn)椴皇撬械淖址伎梢赞D(zhuǎn)換成int,所以這個(gè)初始化器是failable的,也就是說(shuō)它返回一個(gè)可選的int(Int?
)而不僅僅是一個(gè) Int
.最好的辦法是使用 if let
解開這個(gè)可選項(xiàng).
Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (Int?
) instead of just an Int
. The best thing to do is unwrap this optional using if let
.
我不確定你到底想要什么,但這段代碼在 Swift 2 中工作,并完成了我認(rèn)為你正在嘗試做的事情:
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)
}
或者,對(duì)于更快捷的解決方案:
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]
您可以使用 flatMap
進(jìn)一步縮短它:
You can shorten this more with flatMap
:
let fileLines = unsolved.characters.flatMap { Int(String($0)) }
flatMap
返回一個(gè) Array
,其中包含將 transform
映射到 self
的非零結(jié)果"……所以當(dāng) Int(String($0))
為 nil
時(shí),結(jié)果被丟棄.
flatMap
returns "an Array
containing the non-nil results of mapping transform
over self
"… so when Int(String($0))
is nil
, the result is discarded.
這篇關(guān)于在 Swift 2.0 中將字符轉(zhuǎn)換為 Int的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!