使用Swift,我尝试在应用程序的文本视图中输入数字列表,并通过提取成绩计算器的每个数字来创建此列表的总和。此外,用户输入的值的数量也会发生变化。示例如下所示:
字符串:98,99,97,96 ...... 试图得到:98 + 99 + 97 + 96 ...
请帮忙! 感谢
答案 0 :(得分:61)
components(separatedBy:)
分隔以逗号分隔的字符串。trimmingCharacters(in:)
删除每个元素前后的空格Int()
将每个元素转换为整数。compactMap
(以前称为flatMap
)删除无法转换为Int
的所有项目。使用reduce
汇总Int
。
let input = " 98 ,99 , 97, 96 "
let values = input.components(separatedBy: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
let sum = values.reduce(0, +)
print(sum) // 390
答案 1 :(得分:29)
Swift 3 和 Swift 4 。
简单方法:硬编码。仅在您知道要出现的整数的确切数量时才有用,希望进一步计算和打印/使用。
let string98: String = "98"
let string99: String = "99"
let string100: String = "100"
let string101: String = "101"
let int98: Int = Int(string98)!
let int99: Int = Int(string99)!
let int100: Int = Int(string100)!
let int101: Int = Int(string101)!
// optional chaining (if or guard) instead of "!" recommended. therefore option b is better
let finalInt: Int = int98 + int99 + int100 + int101
print(finalInt) // prints Optional(398) (optional)
作为一种功能的花哨方式:通用方式。在这里,您可以根据需要添加尽可能多的字符串。例如,您可以先收集所有字符串,然后使用数组计算它们。
func getCalculatedIntegerFrom(strings: [String]) -> Int {
var result = Int()
for element in strings {
guard let int = Int(element) else {
break // or return nil
// break instead of return, returns Integer of all
// the values it was able to turn into Integer
// so even if there is a String f.e. "123S", it would
// still return an Integer instead of nil
// if you want to use return, you have to set "-> Int?" as optional
}
result = result + int
}
return result
}
let arrayOfStrings = ["98", "99", "100", "101"]
let result = getCalculatedIntegerFrom(strings: arrayOfStrings)
print(result) // prints 398 (non-optional)
答案 2 :(得分:5)
let myString = "556"
let myInt = Int(myString)