我需要一个函数来将数字0到9连续替换为字母A到J。请问在Swift 3中如何编写这个函数? Swift 3字符串操作非常奇怪:| 我尝试访问字符并添加偏移量(移位)字符,但没有成功。
这里提供了一个可能解决您问题的方案,同时保证Unicode安全:
let string = "0123456789 abc xyz 9876543210"
// upper case A...J use 65; lower case a...j use 97
let shift = 65
let convertedString = String(string.characters.lazy.map{ char in
Int(String(char)).map{ Character(UnicodeScalar($0 + shift)!) } ?? char
})
将字符串中的每个字符映射到另一个(或同一)字符:0...9 -> A...J,其他字符保持不变。
为了处理大型字符串,使用懒字符集提高性能。非懒惰的字符集会创建一个中间数组。
从一个字符映射到另一个字符的过程如下:
Try to convert the character to an Int
(Here Int?
)
1.1 If it fails (is nil
) the nil coalescing operator (??
) comes in to play and the input character is returned
The Int value ($0
) now gets converted back to a Character through its (shifted) ASCII representation
Convert the lazily mapped collection to a String
. Swifts declaration of the initialiser:
public init<S : Sequence>(_ characters: S)
where S.Iterator.Element == Character { ... }
lazy
进行映射?这样做有什么优势? - Noah Wilderlazy
,则会创建一个字符的中间数组,如果字符串本身很长,则需要大量的内存。请参见上面的实现部分以获取完整的解释。 - Qbyte