我有一个数组值为字符串(但所有字符串都是1.0,2.0等值)。我正在尝试将这些字符串转换为双精度或浮点数,因此我可以将它们全部添加到一起。我如何在swift中做到这一点?
答案 0 :(得分:5)
let x = ["1.0", "1.5", "2.0"]
print(x.map {Double($0)!})
答案 1 :(得分:4)
更新: 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) }
}
}
用法:
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
如果你有一个Any数组?您需要将所有字符串从Optional Any转换为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 ?? "") }
}
}
用法:
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 :(得分:1)
如果您确定所有数组都是字符串,则可以直接将字符串转换为float或double。
let numberArray:Array = ["1.0","2.0","3.0"]
let stringFromArray = numberArray[0]
let floatFromString = Float(stringFromArray)
let doubleFromString = Double(stringFromArray)
答案 3 :(得分:1)
Swift 5.1
extension Collection where Iterator.Element == String {
var convertToDouble: [Double] {
return compactMap{ Double($0) }
}
var convertToFloat: [Float] {
return compactMap{ Float($0) }
}
}
示例用法
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]
或您可以执行此操作
let numArray = ["1.0","2.0","3.0"]
let stringFromArray = numberArray[0]
let floatFromString = Float(stringFromArray)
let doubleFromString = Double(stringFromArray)