Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Convert values in array to doubles or floats

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?

like image 287
somepers Avatar asked Dec 05 '22 01:12

somepers


2 Answers

let x = ["1.0", "1.5", "2.0"]
print(x.map {Double($0)!})
like image 55
BallpointBen Avatar answered Dec 14 '22 07:12

BallpointBen


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
like image 27
Leo Dabus Avatar answered Dec 14 '22 07:12

Leo Dabus