我想比较UITextField
中的两个条目,为每个字母添加一个数字,然后比较两个字母中字母的添加结果。
示例:
a = 1 b = 2 c = 3 d = 4 e = 5 f = 6
textfield1 = cae
textfield2 = fca结果是:
textfield1 = 9和
文本字段2 = 10
答案 0 :(得分:0)
您可以使用每个字符的unicode标量表示(查找ASCII表)并将这些值移位-96
(例如a -> 1
,b -> 2
等等)。在下文中,大写字母将生成与小写字母相同的数字值。
let foo = "cae"
let pattern = UnicodeScalar("a")..."z"
let charsAsNumbers = foo.lowercaseString.unicodeScalars
.filter { pattern ~= $0 }
let sumOfNumbers = charsAsNumbers
.reduce(0) { $0 + $1.value - 96 }
print(sumOfNumbers) // 9
或者,为了简化使用,请创建一个函数或String
扩展名
/* as a function */
func getNumberSum(foo: String) -> UInt32 {
let pattern = UnicodeScalar("a")..."z"
return foo.lowercaseString.unicodeScalars
.filter { pattern ~= $0 }
.reduce(0) { $0 + $1.value - 96 }
}
/* or an extension */
extension String {
var numberSum: UInt32 {
let pattern = UnicodeScalar("a")..."z"
return self.lowercaseString.unicodeScalars
.filter { pattern ~= $0 }
.reduce(0) { $0 + $1.value - 96 }
}
}
您案例的用法示例:
/* example test case (using extension) */
let textField1 = UITextField()
let textField2 = UITextField()
textField1.text = "cAe"
textField2.text = "FCa"
/* example usage */
if let textFieldText1 = textField1.text,
let textFieldText2 = textField2.text {
print(textFieldText1.numberSum) // 9
print(textFieldText2.numberSum) // 10
print(textFieldText1.numberSum
== textFieldText2.numberSum) // false
}