Search code examples
iosswiftmacosoperator-overloading

How to make a custom function with + operator in Swift


I'm looking at this code from rosettacode.org and one of the functions defined within it is this:

class MyClass {
    static func + <T>(el: T, arr: [T]) -> [T] {
        var ret = arr
    
        ret.insert(el, at: 0)
    
        return ret
    }
}

The compiler has this to say about it:

Member operator '+' must have at least one argument of type 'MyClass'

I updated the method to make it it static, as follows:

static func + <T: Sequence>(el: T, arr: [T]) -> [T] {
    var ret = arr
    
    ret.insert(el, at: 0)
    
    return ret
}

That doesn't get rid of the compiler error. I tried Googling it, but I'm not coming up with any short, simple answers. Any ideas how I might quell this error?


Solution

  • As explained by @MartinR in the comments, you need to put this function at the top level (NOT inside a class).

    import Foundation
    
    // Will compile fine from here as is
    func + <T>(el: T, arr: [T]) -> [T] {
        var ret = arr
        ret.insert(el, at: 0)
        return ret
    }
    
    class TableGenerator {
        // will require at least one argument of the function to be of `TableGenerator` type
    }