简体   繁体   English

Swift委托作为函数参数

[英]Swift delegate as a function parameter

I created my protocol as below: 我创建了如下协议:

import Foundation
protocol ITcpCLient: class {
    func OnMessageReceived(_ message: String);
}

The class using protocol as below: 使用协议的类如下:

import Foundation

class tcpConnection {
    var tcpClientdelegate: ITcpCLient?

    init(client: ITcpCLient) {
        self.tcpClientdelegate? = client

        if self.tcpClientdelegate == nil {
            print("tcpClient Delegate is nil!")
        }
    }

    func trigger() {
        tcpClientdelegate?.OnMessageReceived("From Trigger")
    }

}

My ViewController Class is below: 我的ViewController类如下:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("viewDidLoad!")
        let myTcpConnection = tcpConnection(client: self)
        myTcpConnection.trigger()
    }


}


extension ViewController: ITcpCLient {

    func OnMessageReceived(_ message: String) {
        print("onMessageReceived")
        print(message)
    }

}

The output is: tcpClient Delegate is nil! 输出为:tcpClient代表为零! If I create delegate without question mark, the code working as expected.But when I use optional type, I cant assign viewcontroller class as a delegate. 如果我创建没有问号的委托,代码将按预期工作。但是当我使用可选类型时,我无法将viewcontroller类分配为委托。

Since self.tcpClientdelegate is nil then appending ? 由于self.tcpClientdelegatenil因此追加? operator will cause whole statement not to be run => which causes that delegate to be un-assinged = nil 运算符将导致整个语句无法运行=>这将导致该委托被取消声明= nil

self.tcpClientdelegate? = client

so replace with 所以换成

self.tcpClientdelegate = client

The problem lies in the init : 问题出在init

self.tcpClientdelegate? = client

The postfix ? 后缀? operator will not carry out whatever operation you specified if its operand is nil . 如果操作数为nil则该操作符将不执行您指定的任何操作。

Here, self.tcpClientdelegate is nil, so the value is not assigned. 在这里, self.tcpClientdelegate为零,因此未分配该值。

From the Swift Language Reference : Swift语言参考中

Optional-chaining expressions must appear within a postfix expression, and they cause the postfix expression to be evaluated in a special way. 可选链接表达式必须出现在后缀表达式中,并且它们使后缀表达式以特殊方式求值。 If the value of the optional-chaining expression is nil, all of the other operations in the postfix expression are ignored and the entire postfix expression evaluates to nil. 如果可选链表达式的值为nil,则后缀表达式中的所有其他操作将被忽略 ,整个后缀表达式的求值为nil。

Just assign it normally to fix the problem, because you don't care about whether self.tcpClientdelegate was nil or not: 只需正常分配它即可解决问题,因为您不必关心self.tcpClientdelegate是否为nil

self.tcpClientdelegate = client

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

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