swift - 为什么 self 在 init() 方法中被允许,即使它未通过安全检查?

标签 swift

Safety Check #4

An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.

class Fruit {
  var name: String
  init(fruitName: String) {
    // in phase one
    self.name = fruitName; // using self during the property assignment
    // phase one is complete
  }
}

let orange = Fruit(fruitName: "Orange");

那么,如何获得使用 self 的特殊权限,并知道 self 指代的是什么?

最佳答案

or refer to self as a value until after the first phase of initialization is complete.

这是第一阶段准备好的情况,您希望如何在没有 self 的情况下分配实例的属性?一个更有用的示例是当您重写 init 方法时。

在 super.init() 之前不能使用 self

关于swift - 为什么 self 在 init() 方法中被允许,即使它未通过安全检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31010356/

相关文章:

ios - Storyboard?.instantiateViewController(withIdentifier : "") as! viewcontroller

javascript - 如何使用 SwiftSoup 抓取重定向的特定网站?

ios - 使用 TableViewController 创建双委托(delegate)

swift - 即使我使用 .randomElement() 方法 (Swift) 2019/2020,每日提醒(通知)也不会发送随机消息

ios - 文本字段为空时禁用 UIAlertView 中的按钮

ios - 如何在 Swift 中使用 Parse 创建 PFQueryTableViewController?

ios - 在实例化时从按下状态开始 UIPanGesture 事件

ios - 如果将代码共享给其他系统,我是否需要在代码中安装 alamofire

swift - 为什么 Realm 建议使用 "let"声明 List<T> 属性?

ios - 如何在 SwiftUI 中迭代/foreach 数组