将数组中的值转换为双精度或浮点数

将数组中的值转换为双精度或浮点数

本文介绍了Swift - 将数组中的值转换为双精度或浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其值为字符串(但所有的字符串都是1.0,2.0等等)。我正在尝试将这些字符串转换为双精度或浮点数,因此我可以将它们全部加在一起。如何在swift中执行此操作?

解决方案

更新: Xcode 8.3.2•Swift 3.1 / p>

 扩展集合其中Iterator.Element == String {
var doubleArray:[Double] {
return flatMap {Double($ 0)}
}
var floatArray:[Float] {
return flatMap {Float($ 0)}
}
}

用法:

  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

如果你有一个数组的任何?您需要将所有字符串从Optional Any转换为Double:

 扩展集合其中Iterator.Element == Any? {
var doubleArrayFromStrings:[Double] {
return flatMap {Double($ 0 as?String ??)}
}
var floatArrayFromStrings:[Float] {
return flatMap {Float($ 0 as?String ??)}
}
}

用法:

  let strNumbersArray:[Any?] = [1.5,2.3,3.7 ,4.5,nil] // [{Some1.5},{Some2.3},{Some3.7},{Some4.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


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?

解决方案

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

这篇关于Swift - 将数组中的值转换为双精度或浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:29