Swift类“MyClass”没有名为“My_Var”的成员 [英] Swift class "MyClass" does not have a member Named "My_Var"

查看:190
本文介绍了Swift类“MyClass”没有名为“My_Var”的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中创建了一个类,如下所示,但它给出了错误:

I created a class in Swift like below, but it gives error:


'ApiUrls.Type'没有名为的成员'webUrl'

'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 在初始化所有实例属性之前不可用。

You cannot initialize an instance property with the value of another property, because self is not available until all instance properties have been initialized.

Even在初始化程序中移动属性初始化不起作用,因为 getKey 依赖于 webUrl ,所以 getKey 在init为自身之前无法初始化ialized。

Even moving the properties initialization in an initializer doesn't work, because getKey relies on webUrl, so getKey cannot be initialized until itself is initialized.

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

I see that webUrl is a constant, so maybe it's a good idea to make it a static property - classes don't support statics as of yet, so the best way is to use a private struct:

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

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

}

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

Also, unless you have a good reason, it's better to use swift strings and not NSString.

这篇关于Swift类“MyClass”没有名为“My_Var”的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆