问题
c is a Character variable in Swift that I happen to know contains a digit from 1 to 9. I want to decrement the value of the digit stored in c, and this is the best I could come up with:
c = Character(String(Int(String(c))! - 1))
Which seems insanely convoluted. Is there a better way?
回答1:
This sounds like a perfect use for UnicodeScalar:
let scalar = UnicodeScalar("8")
let char = Character(UnicodeScalar(scalar.value-1)) // "7"
Or, more verbosely from a character variable:
let c = Character("8")
let str = String(c)
if let scalar = str.unicodeScalars.first {
let char = Character(UnicodeScalar(scalar.value-1)) // "7"
}
This is pretty messy, as we have to convert the Character into a String, then a UnicodeScalar, and then back to a Character. I'll keep working for towards a better solution.
I've figured out why the UnicodeScalar constructor works with a String literal.
There is a private initializer for _NSSimpleObjCType (which conforms to UnicodeScalar) which takes a the first character of a String and passes it to the rawValue constructor.
NSObjCRuntime.swift
extension _NSSimpleObjCType {
init?(_ v: UInt8) {
self.init(rawValue: UnicodeScalar(v))
}
init?(_ v: String?) {
if let rawValue = v?.unicodeScalars.first {
self.init(rawValue: rawValue)
} else {
return nil
}
}
}
回答2:
You can create an extension as follow:
extension Character {
var integerValue: Int {
return Int(String(self)) ?? 0
}
var predecessor: Character {
return integerValue.predecessor() < 0 ? "0" : String(integerValue.predecessor()).characters.first!
}
}
var c: Character = "9"
c = c.predecessor
print(c) // "8"
来源:https://stackoverflow.com/questions/35489690/how-to-decrement-a-character-that-contains-a-digit