我开始学习Swift语言,我非常好奇Swift中的字符串和字符比较对语言环境不敏感是什么意思?这是否意味着所有字符都以UTF-8字符存储在Swift中?
我试图扩展Character到符合Strideable以创建CountableClosedRange的Character类型。最后,我想要打印整个字母表的类似内容:
("A"..."Z").forEach{
print($0)
}
Run Code Online (Sandbox Code Playgroud)
目前,我使用UnicodeScalar类型来计算两个字符之间的距离。因为Character类型中没有标量,所以我需要从字符创建一个字符串,获取第一个标量的值,并计算它们之间的距离:
extension Character: Strideable {
func distance(to other: Character) -> Character.Stride {
return abs(String(self).unicodeScalars.first?.value - String(other).unicodeScalars.first!.value)
}
func advanced(by n: Character.Stride) -> Character {
return Character(UnicodeScalar(String(self).unicodeScalars.first!.value + n))
}
}
Run Code Online (Sandbox Code Playgroud)
即使这样,我也会收到Character不符合协议Strideable和_Strideable. 编译器似乎没有选择Stride随附的关联类型Strideable:
public protocol Strideable : Comparable {
/// A type that can represent the distance between two values of `Self`.
associatedtype Stride : …Run Code Online (Sandbox Code Playgroud)