Instance member can not be used in swift

时间:2016-04-25 09:14:55

标签: ios json swift instance

The project is to create a JSON object.

code is below :

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
            ]
    }
}

This line always appears Error

2 个答案:

答案 0 :(得分:1)

appID is a instance variable but getJSONObject is a class method. So it will not work. You have to redesign it somehow.

答案 1 :(得分:1)

1

You declare "getJSONObject" class (not a method) derived from RegisterIn class inside super class. Why?

2

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

you can use const values here but not instance memeber (of derived class)

3

this code works in 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")