假设我们有这个 viewController
public class DetailsViewController : UITableViewController
{
public var text : String;
public override func viewDidLoad ( )
{
// do something with text
}
}
我们还有另一个 Controller ,可以通过 segue 推送前一个 Controller
public class MainViewController : UITableViewController
{
...
public override func prepareForSegue ( segue : UIStoryboardSegue, sender : AnyObject? )
{
if ( segue.identifier == "detailsSegue" )
{
let selectPatientController = segue.destinationViewController as! DetailsViewController;
selectPatientController.text = "I'm Iron Man";
}
}
}
由于MainViewController没有实例化DetailsViewController,我不能保证“text”会被设置。所以我可以将它声明为“String”?或“字符串!”。
“字符串?”:我必须写“.text?”在 viewDidLoad 中。如果 MainViewController 没有设置该属性,我可能会得到一个缺少文本的 View 。
“String!”:代码更简单,但如果 MainViewController 未设置该属性,应用程序会崩溃。
对于可能出现的错误,最佳选择是什么:显示不完整的 View 或崩溃并获取错误日志?最后一个对用户来说不愉快,但它有助于错误跟踪,特别是在开发时间。
我认为一个好的解决方案是使用“String?”使用assert(),然后应用程序只会在开发时间崩溃。还有其他建议吗?
最佳答案
这是我的做法。
是否可以设置默认文本
public class DetailsViewController : UITableViewController
{
public var text : String = "Default text or empty string" {
didSet {
//property was just changed so you can update your UI with new text
//for example (you need to define this function yourself)
self.updateWhenTextChanged()
}
}
public override func viewDidLoad ( )
{
// do something with text
}
}
如果无法设置默认文本
将其保留为字符串?
。解开它可能会很痛苦(尽管在 Swift 2.0 中 guard
语句有很大帮助),但这样你就可以确保你的代码是安全的。
放置String!
可能很诱人,但是如果出于某种原因您将来停止使用segues并且将通过xibs或Apple引入的某些新方法以编程方式加载 View Controller ,该怎么办?想象一下,找到所有这些隐式解包的变量并修复它们将是多么痛苦!
关于null - Swift 中的属性是否应该在我的 UIViewController 中隐式展开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039450/