当您尝试将数组分配给不是数组的内容时,可能会发生此类错误.
例1
let array: Int = [1, 3, 7, 4] // error: contextual type Int cannot be used with array literal
与其名称相反,该常数array
被称为单一Int
.但是然后为它分配了一个实际的数组.这可以通过以下任一方式解决.
let array = [1, 3, 7, 4] let array: [Int] = [1, 3, 7, 4]
例2
当有嵌套数组时,它可能不那么明显:
let array: [Int] = [1, 2, 7, [100, 200, 300]] // error: contextual type Int cannot be used with array literal
对于这个,您需要将其概括为[Any]
.
let array: [Any] = [1, 2, 7, [100, 200, 300]]
您需要以这种方式初始化对象:
class JsonParams { let userName = "root" let password = "admin01" var param = [String: Any]() init() { let param : [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session", "login", [ "username": self.userName, "password": self.password]]] self.param = param } }
编辑:
如果你想让userName
你可以这样做:
class JsonParams { let userName = "root" let password = "admin01" var param = [String: Any]() init() { let param : [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session", "login", [ "username": self.userName, "password": self.password]]] self.param = param } func getUserName() -> String { return self.userName } }
这样你就可以访问:
let json = JsonParams() json.getUserName() //"root"