更新时间:2023-02-05 15:04:09
有多种方法可以做到这一点(componentsSeparatedByString
、NSScanner
、...).这是一个仅使用 Swift 库函数的函数:
There are various method to do that (componentsSeparatedByString
, NSScanner
, ...).
Here is one using only Swift library functions:
let str = "69 - 13"
// split string into components:
let comps = split(str, { $0 == "-" || $0 == " " }, maxSplit: Int.max, allowEmptySlices: false)
// convert strings to numbers (use zero if the conversion fails):
let nums = map(comps) { $0.toInt() ?? 0 }
// compute the sum:
let sum = reduce(nums, 0) { $0 + $1 }
println(sum)