【发布时间】:2017-12-12 00:06:33
【问题描述】:
我想实现这样一个属性,它的值只能读取一次,然后属性应该设置为nil。
我是这样实现的:
private var _readOnce: String?
var readOnce: String? {
get {
let value = _readOnce
_readOnce = nil
return value
}
set {
_readOnce = newValue
}
}
readOnce = "Andrej"
print("read once = \(readOnce)") // prints read once = Optional("Andrej")\n"
print("read once = \(readOnce)") // prints read once = nil\n"
但我觉得使用单独的属性 _readOnce 不是“迅速”/“最优雅”的方式。
有没有人知道一种不同的方式,不需要使用单独的属性?
我可以确认上面的代码有效,只是我觉得用更少的行来实现相同的行为会更优雅。
【问题讨论】:
-
很好奇...你为什么要这样做?
-
我认为我可以使用这种方法对推送通知做出反应,并确保我只做出一次反应。所以我一直在探索这种方法。但现在看来,我将不得不采取不同的方法,因为其他一些事情的表现与我预期的不完全一样。
-
我不知道你的问题的确切问题。但我正在考虑多种其他方法可以解决这个问题 1. 只需具有布尔属性 somewhere 2. 在 iOS 10 中,不同的委托方法使管理您的意图变得更加容易。也就是说,如果您的通知有
content-available : 1,那么您的application(_:didReceiveRemoteNotification:fetchCompletionHandler:)将被调用。如果用户点击通知didreceivenotificationresponse将被调用。如果用户在应用程序中,willPresentNotification将被调用。
标签: swift properties