As already said, because a Character
can be made up of multiple unicode scalars, you cannot accurately determine how many different valid character representations lie between two arbitrary characters, and is therefore not a good candidate for conformance to Stridable
.
One approach to your problem of simply wanting to print out the alphabet is to conform UnicodeScalar
, rather than Character
, to Stridable
– allowing you to work with characters that are represented by a single unicode code point, and advance them based on that code point.
extension UnicodeScalar : Strideable {
public func distance(to other: UnicodeScalar) -> Int {
return Int(other.value) - Int(self.value)
}
/// Returns a UnicodeScalar where the value is advanced by n.
///
/// - precondition: self.value + n represents a valid unicode scalar.
///
public func advanced(by n: Int) -> UnicodeScalar {
let advancedValue = n + Int(self.value)
guard let advancedScalar = UnicodeScalar(advancedValue) else {
fatalError("(String(advancedValue, radix: 16)) does not represent a valid unicode scalar value.")
}
return advancedScalar
}
}
Now you can form a CountableClosedRange<UnicodeScalar>
, and can freely convert each individual element to a Character
or String
if desired:
("A"..."Z").forEach {
// You can freely convert scalar to a Character or String
print($0, Character($0), String($0))
}
// Convert CountableClosedRange<UnicodeScalar> to [Character]
let alphabetCharacters = ("A"..."Z").map {Character($0)}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…