如何用Swift中浮点可转换的数组输入编写泛型函数?

时间:2022-11-12 19:18:45

I am taking my first foray into writing generic functions in Swift. What I am trying to do is write a function that takes an array input of any type as long as that type is convertible to a floating point number. I am wondering if I can leverage some of the Swift standard library protocols to do this. Here is a trivial example (I am searching for what to use as ConvertibleToFloatingPointTypeProtocol):

我正在第一次尝试在Swift中编写泛型函数。我想要做的是编写一个函数,它接受任何类型的数组输入,只要该类型可以转换为浮点数。我想知道我是否可以利用一些Swift标准库协议来做到这一点。这是一个简单的例子(我正在搜索什么用作ConvertibleToFloatingPointTypeProtocol):

func toDoubleArray<T: ConvertibleToFloatingPointTypeProtocol>(array: [T]) -> [Double] {
    var doubleArray = [Double]()
    for arrayItem in array {
        doubleArray.append(Double(arrayItem))
    }
    return doubleArray
}

The compiler error I get from this when I try FloatingPointType, etc. is: "Cannot find an initializer for type 'Double' that accepts an argument list of type '(T)'"

当我尝试使用FloatingPointType等时,我从中得到的编译器错误是:“找不到类型'Double'的初始化器,它接受类型'(T)'的参数列表”

Now I know another option is to create my own protocol and then extend the types that I am interested in to adopt it, but this just feels like something that exists right under my nose.

现在我知道另一个选择是创建我自己的协议,然后扩展我感兴趣的类型来采用它,但这只是感觉就像我的鼻子下面存在的东西。

1 个解决方案

#1


0  

Try FloatLiteralConvertible:

试试FloatLiteralConvertible:

import Darwin

// Swift 2.0
func toDoubleArray<T : FloatLiteralConvertible>(arr : [T]) -> [Double] {
    return arr.flatMap { $0 as? Double }
}

// Swift 1.2
func toDoubleArray<T : FloatLiteralConvertible>(arr : [T]) -> [Double] {
    var result = [Double]()

    for a in arr {
        if let d = a as? Double {
            result.append(d)
        }
    }

    return result
}

let a = toDoubleArray([1, 2, 3])
let b = toDoubleArray([M_PI, 2 as Int, 3.3])
let c = toDoubleArray(["a", "b", "c"])  // Error, cannot convert [String] to [Double]
let d = toDoubleArray([1, 2, 3, "a"])   // Error, cannot convert [NSObject] to [Double]

#1


0  

Try FloatLiteralConvertible:

试试FloatLiteralConvertible:

import Darwin

// Swift 2.0
func toDoubleArray<T : FloatLiteralConvertible>(arr : [T]) -> [Double] {
    return arr.flatMap { $0 as? Double }
}

// Swift 1.2
func toDoubleArray<T : FloatLiteralConvertible>(arr : [T]) -> [Double] {
    var result = [Double]()

    for a in arr {
        if let d = a as? Double {
            result.append(d)
        }
    }

    return result
}

let a = toDoubleArray([1, 2, 3])
let b = toDoubleArray([M_PI, 2 as Int, 3.3])
let c = toDoubleArray(["a", "b", "c"])  // Error, cannot convert [String] to [Double]
let d = toDoubleArray([1, 2, 3, "a"])   // Error, cannot convert [NSObject] to [Double]