ios – Swift类“MyClass”没有名为“My_Var”的成员[复制]

参见英文答案 > How to initialize properties that depend on each other4个
我在Swift中创建了一个类,如下所示,但它给出了错误

‘ApiUrls.Type’ does not have a member named ‘webUrl’

这是我的代码

import UIKit

class ApiUrls {

    let webUrl:Nsstring = "192.168.0.106:8888"
    var getKey:Nsstring = webUrl + Nsstring("dev/sys/getkey") // here comes the error ApiUrls.Type' does not have a member named 'webUrl

}

这有什么不对?

解决方法

您无法使用另一个属性的值初始化实例属性,因为在初始化所有实例属性之前,self不可用.

即使在初始化程序中移动属性初始化也不起作用,因为getKey依赖于webUrl,因此在初始化之前无法初始化getKey.

我看到webUrl是一个常量,所以也许让它成为一个静态属性是个好主意 – 类到目前为止还不支持静态,所以最好的方法是使用私有结构:

class ApiUrls {
    private struct Static {
        static let webUrl: String = "192.168.0.106:8888"
    }

    var getKey: String = Static.webUrl + "dev/sys/getkey"

}

另外,除非你有充分的理由,否则最好使用swift字符串而不是Nsstring.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...