mozharovsky
mozharovsky

Reputation: 1265

Method signature processing in Swift

I just met a pretty weird issue working with protocols in Swift. The issue is inside of processing signatures of methods. Let's say we've got 2 methods' declarations in our protocol then both of them may be ultimately the same. In order to avoid existence of 2 equal methods or their declarations Swift compiler checks it out while compiling a program but it works weird.

Now let's take a look at the code. My protocol.

@objc
protocol MyProtocol {
    optional func MyProtocol(data: Data, numberOfDays calendar: Calendar) -> Int
    optional func MyProtocol(data: Data, numberOfWeeks calendar: Calendar) -> Int
}

And now since both methods are optional let's implement only one of them.

class CalendarView: UIView, MyProtocol {
    func MyProtocol(data: Data, numberOfDays calendar: Calendar) -> Int {
        return 31
    }
}

It should work but in fact it does not. Compiler says:

Method '...' has different argument names from those required by protocol 'MyProtocol' '...'.

It simply offers to swap method's signature to the second one. Though if you implement both methods all issues will be thrown away!

Does anybody know how to solve that issue? Thank you in advance!

Upvotes: 0

Views: 429

Answers (1)

matt
matt

Reputation: 535547

If you stop calling your function MyProtocol the problem will go away.

(Either that or there is something wrong with your Data or Calendar types.)

I replaced your Data and Calendar types with real types NSData and NSCalendar, and your wacky MyProtocol function name with f, and it compiles just fine:

@objc
protocol MyProtocol {
    optional func f(data: NSData, numberOfDays calendar: NSCalendar) -> Int
    optional func f(data: NSData, numberOfWeeks calendar: NSCalendar) -> Int
}

class CalendarView: UIView, MyProtocol {
    func f(data: NSData, numberOfDays calendar: NSCalendar) -> Int {
        return 31
    }
}

Upvotes: 1

Related Questions