为什么我不能将局部类变量传递给 Swift 中新实例化的类?



我有一个类作为波纹管,其中包含baseUrlapollo

class ViewController: UIViewController {
private let baseUrl = "http://myserver.org:4000"
private let apollo = ApolloClient(url: URL(string: "http://myserver.org:4000")!)
}

请注意,http://myserver.org:4000在两者之间共享,因此我喜欢共享它们

我都试过了

private let apollo = ApolloClient(url: URL(string: baseUrl)!)
// This error out stating 
// `Cannot use instance member 'baseUrl' within property initializer; 
// property initializers run before 'self' is available`

private let apollo = ApolloClient(url: URL(string: self.baseUrl)!)
// This error out stating 
// `Value of type '(ViewController) -> () -> ViewController' has no member 'baseUrl'`

我怎样才能让他们分享?我认为在语言中将常量变量传递给使用它的另一个类很简单。(对不起,我对 Swift 不是很熟悉,如果这很简单的话,因为我更喜欢 Android 开发(。

你可以baseUrl设为静态:

private static let baseUrl = "http://myserver.org:4000"
private let apollo = ApolloClient(url: URL(string: ViewController.baseUrl)!)

错误消息说在完全初始化之前不能使用实例成员self,如果您考虑一下,这很公平,因此我们将其设置为静态。

或者,在初始化器中执行此操作:

private let baseUrl : String = "http://myserver.org:4000"
private let apollo: ApolloClient
required init?(coder: NSCoder) {
apollo = ApolloClient(url: URL(string: baseUrl)!)
super.init(coder: coder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
apollo = ApolloClient(url: URL(string: baseUrl)!)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

为什么不能直接使用baseUrl

这里对此进行了简要说明:

如果使用闭包初始化

属性,请记住,在执行闭包时,实例的其余部分尚未初始化。这意味着您无法从闭包中访问任何其他属性值,即使这些属性具有默认值也是如此。也不能使用隐式 self 属性,也不能调用实例的任何方法。

虽然你在这里并没有真正使用闭包,但想法是相同的。原因仍然适用。请注意,这与 Java 不同,Java 中的字段按文本顺序初始化,因此可以执行以下操作:

private int a = 1;
private int b = a + 1;
private int c = b + 2;

但在 Swift 中,没有指定初始化属性的顺序。

根据初始化规则,不允许初始化相互依赖的常量属性。

或者,延迟初始化apollo,这意味着在第一次访问时创建实例

class ViewController: UIViewController {
private let baseUrl = URL(string:"http://myserver.org:4000")!
private lazy var apollo = ApolloClient(url: baseUrl)    
}

只有variables可以延迟初始化,但由于变量是私有的,因此不相关。

最新更新