swift 中不能使用实例成员

Instance member can not be used in swift

该项目是创建一个 JSON 对象。

代码如下:

public class RegisterIn {

    private var appID : String = ""                             

    private static let JK_appID : String = "appID"

    init(appID: String) {
        self.appID = appID
    }

    class getJSONObject : RegisterIn {
        let jsonObject : [String : AnyObject] =
            [ 
                JK_appID : appID   //< The following error shows on this line
            ]
    }
}

这一行总是出现

appID 是实例变量,而 getJSONObject 是 class 方法。所以它不会工作。你必须以某种方式重新设计它。

1

您声明“getJSONObject”class(不是方法),它派生自 RegisterIn class 内部的 super class。为什么?

2

let jsonObject : [String : AnyObject] =
        [ 
            RegisterIn.JK_appID : appID   
        ]

您可以在此处使用 const 值,但不能使用实例成员(派生的 class)

3

此代码适用于 playground:

import UIKit

public class RegisterIn {
    
    var appID : String = ""
    
    private static let JK_appID : String = "appID"
    
    init(appID: String) {
        self.appID = appID
    }
    
}

class getJSONObject : RegisterIn {
    let jsonObject : [String : AnyObject]
    override init(appID: String) {
        jsonObject =
            [
                RegisterIn.JK_appID : appID
        ]
        super.init(appID: appID)
    }
}

let testGetJSONObject = getJSONObject(appID: "test")