Convert Character to Int in Swift 2.0

夙愿已清 提交于 2019-11-26 18:13:00

问题


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)
}

回答1:


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 an Int. The best thing to do is unwrap this optional using if 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 "an Array containing the non-nil results of mapping transform over self"… so when Int(String($0)) is nil, the result is discarded.




回答2:


This is a bit of improvisational trick I came up with. Since it can be tricky to convert Character to Int, but you can easily convert String to Int do this :

fileLines = Int(String(i))!

of course this is not very well optimized but for cases like yours it can do the trick.




回答3:


Actually. A simpler way is to convert String to Int in Swift 2.o is:

let chars = Int(chars)

Not sure if this is what you're trying for...But you can easily apply this to your loop, of course.




回答4:


Swift 4 solutions

To convert a Character to a String:

let digit = Int(String("1"))! 
//Don't force unwrap this if you're not 100% sure your character is a digit

Solution to OPs problem:

let fileLines = unsolved.compactMap{ Int(String($0) }
// fileLines = [1, 2, 3]



回答5:


In the latest Swift versions (at least in Swift 5) you don't need to do additional conversion to String.

Character has property wholeNumberValue which tries to convert a character to Int and returns nil if the character does not represent and integer.

let char: Character = "5"
if let intValue = char.wholeNumberValue {
    print("Value is \(intValue)")
} else {
    print("Not an integer")
}


来源:https://stackoverflow.com/questions/30771119/convert-character-to-int-in-swift-2-0

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