ios - Swift 类 "MyClass"没有名为 "My_Var"的成员

标签 ios swift

<分区>

我在 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 是一个常量,所以将它设为静态属性可能是个好主意 - 类目前还不支持静态,所以最好的方法是使用私有(private)属性结构:

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

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

}

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

关于ios - Swift 类 "MyClass"没有名为 "My_Var"的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423906/

相关文章:

ios - 使用 adjustsFontSizeToFitWidth 时 UILabel 文本的底部被截断

ios - 使用 fit to width 时设置多个 UIButton 的字体大小相等

ios - MCNearbyServiceBrowser 如何知道 MCNearbyServiceAdvertiser 是否拒绝了邀请?

ios - NSManagedObjectContext -保存: causing SIGSEGV crash

ios - 快速 3 迁移后 NSPredicate 崩溃

ios - swift 2 : @objc protocol and enum array

swift - collisionBitMask 不起作用

ios - 在 iOS 8 键盘中选择时检测笑脸和地球仪

ios - 使用 UIImageview 创建网格

swift - Sqlite.Swift 不明确的列名 Swift