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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With