I have an array with values which are strings (but all the strings are values like 1.0, 2.0, etc). I'm trying to convert those strings into doubles or floats so I can add them all together. How do I do this in swift?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
update: Xcode 8.3.2 • Swift 3.1
extension Collection where Iterator.Element == String {
var doubleArray: [Double] {
return flatMap{ Double($0) }
}
var floatArray: [Float] {
return flatMap{ Float($0) }
}
}
usage:
let strNumbersArray = ["1.5","2.3","3.7","4.5"] // ["1.5", "2.3", "3.7", "4.5"]
let doublesArray = strNumbersArray.doubleArray // [1.5, 2.3, 3.7, 4.5]
let floatsArray = strNumbersArray.floatArray // [1.5, 2.3, 3.7, 4.5]
let total = doublesArray.reduce(0, +) // 12
let average = total / Double(doublesArray.count) // 3
If you have an Array of Any? where you need to convert all strings from Optional Any to Double:
extension Collection where Iterator.Element == Any? {
var doubleArrayFromStrings: [Double] {
return flatMap{ Double($0 as? String ?? "") }
}
var floatArrayFromStrings: [Float] {
return flatMap{ Float($0 as? String ?? "") }
}
}
usage:
let strNumbersArray:[Any?] = ["1.5","2.3","3.7","4.5", nil] // [{Some "1.5"}, {Some "2.3"}, {Some "3.7"}, {Some "4.5"}, nil]
let doublesArray = strNumbersArray.doubleArrayFromStrings // [1.5, 2.3, 3.7, 4.5]
let floatsArray = strNumbersArray.floatArrayFromStrings // [1.5, 2.3, 3.7, 4.5]
let total = doublesArray.reduce(0, +) // 12
let average = total / Double(doublesArray.count) // 3
回答2:
let x = ["1.0", "1.5", "2.0"]
print(x.map {Double($0)!})
回答3:
if you are sure that all of your array is string, you can directly cast your string into float or double.
let numberArray:Array = ["1.0","2.0","3.0"]
let stringFromArray = numberArray[0]
let floatFromString = Float(stringFromArray)
let doubleFromString = Double(stringFromArray)