vac*_*ama 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
Run Code Online (Sandbox Code Playgroud)Dav*_*eek 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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
print(result) // prints 398 (non-optional)