简体   繁体   English

Swift中的协议声明-Xcode 6 beta 5

[英]Protocol declaration in Swift - Xcode 6 beta 5

With Xcode 6 beta 5 protocol and delegate doesn't work like first. 使用Xcode 6 beta 5协议和委托时,委托代理不能像第一个那样工作。 printCar() is not invoked when self.delegate?.printCar() it's called. printCar()self.delegate?.printCar(),它被称为是不被调用。 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")
    }
}

You aren't setting the car's delegate property, so there's no object to call printCar() on. 您没有设置汽车的delegate属性,因此没有对象可以调用printCar()

Also, it's convention to use initial caps for type names in Swift. 另外,习惯上在Swift中使用初始大写作为类型名称。 (You'll notice that it's such strong convention that even SO's syntax highlighter expects it.) (您会注意到,它是如此强大的约定,甚至SO的语法突出显示都期望它。)

BTW, it has nothing to do with this issue, but you might want to be on Xcode 6 beta 6 by now. 顺便说一句,它与此问题无关,但是您现在可能想要使用Xcode 6 beta 6。

Another unrelated issue: Your car class's delegate property should probably be marked as weak . 另一个不相关的问题:您汽车类的delegate属性可能应该标记为weak Otherwise, if the car's delegate is the object that owns the car, you get a memory leak. 否则,如果汽车的委托人是拥有汽车的对象,则会发生内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM