這是我在 objc 中的函式:
(NSString *)hexForString:(NSString *)string{
NSUInteger charIndex = 0;
for (NSUInteger i = 0; i < string.length; i ){
charIndex = (NSUInteger )[string characterAtIndex:i];
}
NSArray *colors = @[
@"1abc9c", @"2ecc71", @"3498db",
@"9b59b6", @"34495e", @"16a085",
@"27ae60", @"2980b9", @"8e44ad",
@"2c3e50", @"f1c40f", @"e67e22",
@"e74c3c", @"95a5a6", @"f39c12",
@"d35400", @"c0392b", @"bdc3c7",
@"7f8c8d"
];
charIndex %= colors.count;
NSLog(@">>po modulo %lld", charIndex); // output is 13 for "Johny ivan"
return colors[charIndex];
}
現在是斯威夫特:
func hex(for string: String) -> String {
var index = 0
string.forEach { character in
index = character.wholeNumberValue ?? 0
}
let colors = [
"1abc9c", "2ecc71", "3498db",
"9b59b6", "34495e", "16a085",
"27ae60", "2980b9", "8e44ad",
"2c3e50", "f1c40f", "e67e22",
"e74c3c", "95a5a6", "f39c12",
"d35400", "c0392b", "bdc3c7",
"7f8c8d",
]
index %= colors.count
print(" \(index)") // output is 0 for "Johny ivan"
return colors[index]
}
uj5u.com熱心網友回復:
Objective-C 版本基本上將每個字符的 ASCII 值相加(實際上是 UTF16 標量值),而您的 Swift 版本檢查字符是否為數字并回傳該值。“更正確”的方法是迭代character.unicodeScalars并添加它們的.value. 但是String已經有一條捷徑:
for scalar in string.unicodeScalars {
index = scalar.value
}
uj5u.com熱心網友回復:
NSStrings是一系列 UTF-16 代碼單元:
NSString 物件編碼符合 Unicode 的文本字串,表示為 UTF-16 代碼單元序列。所有長度、字符索引和范圍均以 16 位平臺端值表示,索引值從 0 開始。
因此,您的 Objective-C for 回圈正在遍歷 UTF-16 代碼單元,并將每個代碼單元的數值相加。
你可以在 Swift 中做同樣的事情:
for codeUnit in string.utf16 {
index = Int(codeUnit)
}
您也可以將其重寫為reduce:
func hex(for string: String) -> String {
let colors = [
"1abc9c", "2ecc71", "3498db",
"9b59b6", "34495e", "16a085",
"27ae60", "2980b9", "8e44ad",
"2c3e50", "f1c40f", "e67e22",
"e74c3c", "95a5a6", "f39c12",
"d35400", "c0392b", "bdc3c7",
"7f8c8d",
]
let index = string.utf16.reduce(0, { result, acc in result Int(acc) })
% colors.count
print(" \(index)") // output is 0 for "Johny ivan"
return colors[index]
}
您的 swift 代碼回圈遍歷Charactera 的 s String(這是與 UTF-16 代碼單元不同的概念),并將它們wholeNumberValue的 s 相加,即:
此字符表示的數值(如果它表示整數)。
顯然,“Johny ivan”中沒有一個字符代表整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496667.html
上一篇:Selenium-Python-AttributeError:“WebDriver”物件沒有屬性“find_element_by_name”
下一篇:電腦必須打開的設定
