初始化程序只能在swift 3

时间:2017-01-26 06:26:14

标签: swift xcode

我在课堂上编写函数时遇到了问题。我创建了一个带有初始化的类,我尝试创建函数,但是我得到了错误,机智初始化程序,你能帮助我吗?

  

初始值设定项只能在类型中声明。

我的代码:

class JsonParams {
let Login_Token = "00000000000000000000000000000000"
init() {
}

func Jsonrequests (userName: String, password: String){

    let param : [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "call", "params": [ self.Login_Token, "session", "login", [ "username": self.userName, "password": self.password]]]
    self.param = param

    return
}

1 个答案:

答案 0 :(得分:1)

删除空init()并清理代码:

class JsonParams {
    let loginToken = "00000000000000000000000000000000"

    func jsonRequests(userName: String, password: String) -> [String:Any] {

        let params: [String : Any] = ["jsonrpc": "2.0",
                 "id": 1,
                 "method": "call",
                 "params": [ self.loginToken, "session", "login", [ "username": userName, "password": password]]
        ]

        return params
    }
}

Afaics你不想存储params,所以你也可以使用静态版本:

class JsonParams {
    static let loginToken = "00000000000000000000000000000000"

    static func createParams(userName: String, password: String) -> [String:Any] {

        let param: [String : Any] = ["jsonrpc": "2.0",
                                 "id": 1,
                                 "method": "call",
                                 "params": [ self.loginToken, "session", "login", [ "username": userName, "password": password]]
        ]

        return param
    }
}

你可以稍后这样称呼:

let params = JsonParams.createParams(userName: "myName", password: "myPass")

您绝对应该learn Swift并且符合code, naming and style conventions