Swift generics: requiring addition and multiplication abilities of a type

前端 未结 2 1233
不思量自难忘°
不思量自难忘° 2020-12-05 07:57

I\'m trying out some examples from the Swift book, namely the matrix example they have which introduces subscript options. This is the code I have:

struct Ma         


        
2条回答
  •  孤街浪徒
    2020-12-05 08:40

    Here's for your second question (but you really should ask two separate questions):

    @infix func +  (m1: Matrix, m2: Matrix) -> Matrix { ... }
    

    For your first question: before solving it, here's the syntax to define multiple constraints for type parameter:

    struct Matrix {...}
    

    or, as GoZoner writes in the comments:

    struct Matrix> {...}
    

    But we're not going to need it. First, define a new protocol and list the operations that you need. You can even make it extend Equatable:

    protocol SummableMultipliable: Equatable {
        func +(lhs: Self, rhs: Self) -> Self
        func *(lhs: Self, rhs: Self) -> Self
    }
    

    Then, provide extensions for the types that you want to conform. Here, for Int and Double, the extensions are even empty, as the implementation of the needed ops is built-in:

    extension Int: SummableMultipliable {}
    extension Double: SummableMultipliable {}
    

    Then, declare your type constraint on the type parameter:

    struct Matrix { ... }
    

    Finally, you can write stuff like this:

    let intMat = Matrix(rows: 3, columns: 3, initialValue: 0)
    let doubleMat = Matrix(rows: 3, columns: 3, initialValue: 0)
    let i: Int = intMat[0,0]
    let d: Double = doubleMat[0,0]
    

    The last thing you'll need is to insert the type constraint in the definition of your operator:

    @infix func +  (m1: Matrix, m2: Matrix) -> Matrix { ... }
    

提交回复
热议问题