Extend array types using where clause in Swift

后端 未结 7 2009
青春惊慌失措
青春惊慌失措 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条回答
  •  星月不相逢
    2020-11-28 07:50

    So I didn't read the question properly. FloatingPointType is an existing protocol that is implemented by Double, Float and CGFloat, so

    Yes. I did it only yesterday to add a function to SequenceType where the elements had to be Equatable. This is a modification to restrict the elements to Float

    You need to use a where clause. This is my function below.

    public extension SequenceType where Self.Generator.Element: FloatingPointType
    {
        public func splitAt(separator: Generator.Element) -> [[Generator.Element]]
        {
            var ret: [[Generator.Element]] = []
            var thisPart: [Generator.Element] = []
    
            for element in self
            {
                if element == separator
                {
                    ret.append(thisPart)
                    thisPart = []
                }
                else
                {
                    thisPart.append(element)
                }
            }
            ret.append(thisPart)
            return ret
        }
    }
    
    [Float(1), Float(2), Float(3), Float(4)].splitAt(Float(2))
    // returns [[1],[3, 4]]
    [Double(1), Double(2), Double(3), Double(4)].splitAt(Double(3))
    // returns [[1, 2],[4]]
    

    NB I couldn't make this work for an array but SequenceType is more general anyway.

提交回复
热议问题