我想实现这样的属性,它的值只能读取一次,然后属性应设置为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"
但I'feel就像使用一个单独的属性_readOnce
不是“SWIFTY” /“最优雅”的方式来做到这一点。
有谁知道一种不同的方式,那将不需要使用单独的属性?
我可以确认上面的代码有效,只是我觉得它可以更优雅,更少的线条来实现相同的行为。
好奇......你为什么要这么做? – Honey
我以为我可以使用这种方法来反应推送通知,并确保我只反应一次。所以我一直在探索这种方法。但是现在看来,我必须采取不同的方法,因为其他一些事情的行为并不像我期望的那样。 – Andrej
我不知道你的问题的确切问题。但是我正在考虑多种其他方式来解决这个问题1.只需要布尔属性* somewhere * 2.在iOS 10中,不同的委托方法使得管理你想要的更容易。这就是说,如果你的通知有'content-available:1',那么你的应用程序(_:didReceiveRemoteNotification:fetchCompletionHandler :)会被调用。如果用户点击通知“didreceivenotificationresponse”将被调用。如果用户在应用程序中,将会调用'willPresentNotification'。 – Honey