[英]swift: defer non-optional object initialization
When dialing with CocoaTouch, it often happens that UIView(Controller) subclass properties can't be initialized in init
method (ex. we need view already loaded), but logically they are non-optional and even non-var. 使用CocoaTouch拨号时,经常会发生UIView(Controller)子类属性无法在
init
方法中init
(例如,我们需要已加载视图),但是从逻辑上讲,它们是非可选的,甚至是非var。 In such cases the property must be optional to compile without errors, what looks pretty ugly - the code is fulfilled with !
在这种情况下,该属性必须是可选的,才能进行编译而不会出现错误,这看起来很难看-代码用
!
来实现!
. 。
Is there any way to solve this problem? 有什么办法解决这个问题? I would imagine some deferred initialization.
我会想象一些延迟的初始化。 Perfectly if such property can compile without initial value and crash at runtime if it's accessed prior to be initialized.
如果此类属性可以在没有初始值的情况下进行编译,并且如果在初始化之前进行了访问,则在运行时崩溃,则是完美的选择。
Some code sample to describe the issue: 一些代码示例来描述问题:
class MyVC: UIViewController {
@IBOutlet var someLabel: UILabel!
let viewBasedParam: CustomClass // how to keep it non-optional if it can be initialized after view has been loaded?
override func viewDidLoad() {
super.viewDidLoad()
self.viewBasedParam = CustomClass(self.someLabel.text)
}
}
PS CustomClass
can't have default initializer, because it requires data from view. PS
CustomClass
不能具有默认的初始化程序,因为它需要视图中的数据。
In your MyVC
you can have a convenience
init
method where you can initialize the let
variables. 在
MyVC
您可以使用convenience
init
方法来初始化let
变量。 Try this and let me know if it works for you: 试试这个,让我知道它是否适合您:
class MyVC: UIViewController {
let viewBasedParam: CustomClass
convenience init() {
self.init(nibName:nil, bundle:nil)
self.viewBasedParam = CustomClass(self.someLabel.text)//else just initialize with empty string here and then assign actual value in viewDidLoad
}
}
As far as I've discovered the workaround solution may be following: 据我发现,解决方法可能如下:
class MyVC: UIViewController {
@IBOutlet var someLabel: UILabel!
private var _viewBasedParam: CustomClass? = nil
var viewBasedParam: CustomClass {
get { return self._viewBasedParam! } // always unwrap private optional
set { self._viewBasedParam = newValue }
}
override func viewDidLoad() {
super.viewDidLoad()
self.viewBasedParam = CustomClass(self.someLabel.text)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.