gpt4 book ai didi

swift - 初始化阶段 - 这可以更容易地完成吗?

转载 作者:行者123 更新时间:2023-11-28 15:11:46 25 4
gpt4 key购买 nike

我有一个实现 MultipeerConnectivity 的类,我想要一个子类来为广告商实现它。这是我想要的:

class ConnectionManager: NSObject {

let serviceType: String
let peerID: MCPeerID
let session: MCSession
var delegate: ViewController!

override init() {
serviceType = "mc-service"
peerID = MCPeerID(displayName: UIDevice.current.name)
session = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
super.init()
session.delegate = self
}
}

class AdvertiserConnectionManager: ConnectionManager {

let assistant: MCAdvertiserAssistant

override init() {
assistant = MCAdvertiserAssistant(serviceType: serviceType, discoveryInfo: nil, session: session)
super.init()
assistant.delegate = self
assistant.start()
}
}

但这打破了 init() 的分阶段规则,因为 MCAdvertiserAssistant(serviceType:, discoveryInfo:, session:) 使用了 serviceTypesession , 父类(super class)的两个属性。

我已经用子类完成了以下操作,通过懒惰地声明 assistant 作弊。这行得通!为什么?初始化器仍然需要调用self!!!我不得不做这种不自然的事情来创建我的子类。而且我可能已经颠覆了分阶段旨在避免的事情!!

class AdvertiserConnectionManager: ConnectionManager {

lazy var assistant: MCAdvertiserAssistant = {
MCAdvertiserAssistant(serviceType: serviceType, discoveryInfo: nil, session: session)
}()

override init() {
super.init()
assistant.delegate = self
assistant.start()
}
}

最佳答案

你不是作弊,这不是一件不自然的事情。这是初始化相互依赖的对象属性的常用方法。

来自documentation (Swift Language Guide: Properties) :

A lazy stored property is a property whose initial value is not calculated until the first time it is used.
...
Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.

在您的情况下,assistant 将在 super.init 调用之后 初始化,当 self 时, serviceTimesession 有效且可用。

关于swift - 初始化阶段 - 这可以更容易地完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com