Search code examples
iosswiftxcode6-beta5

Protocol declaration in Swift - Xcode 6 beta 5


With Xcode 6 beta 5 protocol and delegate doesn't work like first. printCar() is not invoked when self.delegate?.printCar() it's called. How can I use protocol & delegate now?

import UIKit

protocol communication{
    func printCar()
}

class car{
    var delegate:communication?

    init(){}

    func passCar(){
        self.delegate?.printCar()
    }
}

class ViewController: UIViewController,communication {

    override func viewDidLoad() {
        super.viewDidLoad()
        println("start")
        var bmw = car()
        bmw.passCar()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func printCar(){
        println("car")
    }
}

Solution

  • You aren't setting the car's delegate property, so there's no object to call printCar() on.

    Also, it's convention to use initial caps for type names in Swift. (You'll notice that it's such strong convention that even SO's syntax highlighter expects it.)

    BTW, it has nothing to do with this issue, but you might want to be on Xcode 6 beta 6 by now.

    Another unrelated issue: Your car class's delegate property should probably be marked as weak. Otherwise, if the car's delegate is the object that owns the car, you get a memory leak.