Before upgrading to Xcode 6.4 and Swift 1.2, the following code worked in playground:
@objc protocol Speaker {
func Speak()
optional func TellJoke()
}
class Deb: Speaker {
func Speak() {
println("Hello, I am Deb!")
}
func TellJoke() {
println("Q: What did Sushi A say to Sushi B?")
}
}
class Bryan: Speaker {
func Speak() {
println("Yo, I am Bryan!")
}
func TellJoke() {
println("Q: What's the object-oriented way to become wealthy?")
}
func WriteTutorial() {
println("I'm on it!")
}
}
var speaker:Speaker
speaker = Bryan()
speaker.Speak()
(speaker as Bryan).WriteTutorial()
speaker = Deb()
speaker.Speak()
speaker.TellJoke?()Now after upgrading I had to change the class declarations as below and the optional chaining (line 33 above) always returns nil. In order to get it to work, I have to downcast it to the specific class which sort of defeats the purpose:
@objc protocol Speaker {
func Speak()
optional func TellJoke()
}
class Deb: Speaker {
@objc func Speak() { //had to put @objc in front of required functions in order to compile
println("Hello, I am Deb!")
}
func TellJoke() {
println("Q: What did Sushi A say to Sushi B?")
}
}
class Bryan:Speaker {
@objc func Speak() { //had to put @objc in front of required functions in order to compile
println("Yo, I'm Bryan!")
}
func TellJoke() {
println("Q: What's the object-oriented way to become wealthy? ")
}
func WriteTutorial() {
println("I'm on it!")
}
}
var speaker:Speaker
speaker = Deb()
speaker.TellJoke?() //always returns nil regardless of whether it implements the optional method now.
(speaker as! Deb).TellJoke() //required to get it to call the optional method but seems to defeat the purpose of optional methodsI haven't found any notice/documentation about now having to add @objc before required methods of protocols when implementing them if there is a mix of required and optional methods. In addition, the bigger problem is the optional chaining not working when calling optional methods on an object of a protocol type.
What am I missing?