Extend array types using where clause in Swift

后端 未结 7 2013
青春惊慌失措
青春惊慌失措 2020-11-28 07:35

I\'d like to use the Accelerate framework to extend [Float] and [Double] but each of these requires a different implementation.

I tried the obvious:

         


        
7条回答
  •  旧时难觅i
    2020-11-28 07:53

    How about

    extension CollectionType where Generator.Element == Double {
    
    }
    

    Or If you want a little bit more:

    protocol ArithmeticType {
        func +(lhs: Self, rhs: Self) -> Self
        func -(lhs: Self, rhs: Self) -> Self
        func *(lhs: Self, rhs: Self) -> Self
        func /(lhs: Self, rhs: Self) -> Self
    }
    
    extension Double : ArithmeticType {}
    extension Float : ArithmeticType {}
    
    extension SequenceType where Generator.Element : protocol {
        var sum : Generator.Element {
            return reduce(0.0, combine: +)
        }
    
        var product : Generator.Element {
            return reduce(1.0, combine: *)
        }
    }
    
    
    stride(from: 1.0, through: 10.0, by: 1.0).sum   // 55
    [1.5, 2.0, 3.5, 4.0, 5.5].product               // 231
    

    Works with Double and Float or any other type that you conform to the protocols ArithmeticType and FloatLiteralConvertible. If you need to access specific indices of your array, change SequenceType to CollectionType as you cannot do this with a sequence.

提交回复
热议问题