[英]Swift optional or Implicit property on UIViewController subclass
I have a the following class 我有以下课程
class Foo : UIViewController {
var demo : SKView
override func viewDidLoad() {
...
self.demo = SKView(...)
...
self.view.insertSubview(demo, atIndex: 0)
}
override func viewWillDisappear(animated : Bool) {
self.demo.removeFromSuperView()
self.demo = nil
}
}
My question is, since I don't have an initializer on Foo
, demo has to be either ?
我的问题是,因为我在Foo
上没有初始化器,所以demo必须是?
or !
或者!
. 。 I have read many places that I should stay away from using !
我读过许多我应该远离使用的地方!
. 。 In this case however, is there any reason to not use it? 但是,在这种情况下,有没有理由不使用它? I'm not 100% clear on the downsides specifically on this case since the view itself will always be set on viewDidLoad
and only unset on viewWillDisappear
. 由于视图本身将始终在viewDidLoad
上设置并且仅在viewWillDisappear
上取消设置,因此我不是100%明确了解此案例的缺点。
What is the most common pattern for these kind of properties on such classes? 这类课程中这类属性最常见的模式是什么? Properties that get set on viewDidLoad
and will always have a value. 在viewDidLoad
设置的属性,并且始终具有值。
The reason for this is that Swift enforces class members to always have a value upon initialization. 原因是Swift强制类成员在初始化时始终具有值。 By marking the variable demo
with !
通过标记变量demo
!
or ?
还是?
you are telling the compiler that this variable can have the value nil
, hence the optional notation. 你告诉编译器这个变量的值可以是nil
,因此是可选的表示法。
In the context of iOS development, it's perfectly acceptable to mark SKView
with !
在iOS开发环境中,标记SKView
是完全可以接受的!
so you don't have to suffix each call to demo
with ?
所以你不必后缀每次调用demo
用?
. 。
If demo
is nil
and you require a value to always be present then the app will crash during runtime which under many circumstances is in fact desirable. 如果demo
为nil
并且您需要始终存在值,那么应用程序将在运行时崩溃,在许多情况下实际上是可取的。
class Foo : UIViewController {
var demo : SKView!
override func viewDidLoad() {
...
self.demo = SKView(...)
...
self.view.insertSubview(demo, atIndex: 0)
}
override func viewWillDisappear(animated : Bool) {
self.demo.removeFromSuperView()
self.demo = nil
}
}
class Foo: UIViewController {
var demo: SKView = SKView()
...
}
100% it won't be nil since Foo(). 100%自Foo()以来不会是零。
Or you can override the init(), but I don't like that. 或者你可以覆盖init(),但我不喜欢它。 If I'm sure I won't use the property before ViewDidLoad(), I prefer to writing the initialization in ViewDidLoad(), and mark as var demo: SKView!
如果我确定我不会在ViewDidLoad()之前使用该属性,我更喜欢在ViewDidLoad()中编写初始化,并标记为var demo: SKView!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.