Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour on Swift protocol methods

Just stumbled across a weird behavior in swift when using a protocol with optional methods which have the same name and argument types but differently named parameters.

Everything works fine if I implement none or both of the methods in my class, but as soon as I comment one out, swift complains:

"Method 'myProtocol(foo:)' has different argument names from those required by protocol 'MyProtocol' ('myProtocol(bar:)')"

The behaviour that I would expect is that I can implement an arbitrary combination (only one of the two, both or none) of the protocol methods since both methods are defined as optional.

Here's a playground file to demonstrate the issue, when you un-comment the comments or don't implement any of the protocol methods everything compiles fine.

// Playground - noun: a place where people can play

import UIKit

@objc protocol MyProtocol {
    optional func myProtocol(foo aString: String!)
    optional func myProtocol(bar aString: String!)
}

class Test : MyProtocol {
    init() {

    }

    func myProtocol(foo aString: String!) {
        puts("myProtocol(foo aString: String!): \(aString)")
    }

    // UN-COMMENT THIS AND EVERYTHING COMPILES FINE
    /* 
    func myProtocol(bar aString: String!) {
        puts("myProtocol(bar aString: String!): \(aString)")
    }
    */
}

let foobar = Test()

foobar.myProtocol(foo: "Hello")
//foobar.myProtocol(bar: "Bye")

Can somebody enlighten me on this?

like image 200
sled Avatar asked Aug 14 '14 13:08

sled


1 Answers

As we know from Swift documentation for functions, foo and bar are external names for aString parameter. So technically he have exactly the same function with just different names of parameters that is completely legal in Objective-C:

id<MyProtocol> myVar;
[myVar myProtocolWithBar:@""];
[myVar myProtocolWithFoo:@""];

I think it is a bug in Swift compiler! File a report: http://bugreport.apple.com

like image 133
Keenle Avatar answered Nov 06 '22 20:11

Keenle