Reputation: 529
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?
Upvotes: 5
Views: 11806
Reputation: 519
Swift 5.1
extension Collection where Iterator.Element == String {
var convertToDouble: [Double] {
return compactMap{ Double($0) }
}
var convertToFloat: [Float] {
return compactMap{ Float($0) }
}
}
Example How to Use
let String_Array = ["1.5","2.3","3.7","4.5"] // ["1.5", "2.3", "3.7", "4.5"]
let Double_Array = String_Array.convertToDouble // [1.5, 2.3, 3.7, 4.5]
let Float_Array = String_Array.convertToFloat. // [1.5, 2.3, 3.7, 4.5]
OR You can do this
let numArray = ["1.0","2.0","3.0"]
let stringFromArray = numberArray[0]
let floatFromString = Float(stringFromArray)
let doubleFromString = Double(stringFromArray)
Upvotes: 3
Reputation: 236360
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
Upvotes: 6
Reputation: 1379
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)
Upvotes: 1