我正在尝试创建一个包含请求参数的新类,但我收到错误:
上下文类型any不能与数组文字一起使用
我尝试在最后添加as Any
,但它无效。
class JsonParams {
let userName = "root"
let password = "admin01"
static let param: [String: Any] = [
"jsonrpc": "2.0",
"id": 1,
"method": "call",
"params": [
"00000000000000000000000000000000",
"session",
"login",
[ "username": userName, "password": password]
]
]
}
修改
现在我需要在有人输入之后从用户名文本字段发送用户名和密码到param,所以我想为param创建一个方法,
class JsonParams {
let userName = "root"
let password = "admin01"
var param = [String: Any]()
func log (username.text, password.text){
init() {
let param : [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session", "login", [ "username": username.text, "password": password.text]]]
self.param = param
}
答案 0 :(得分:14)
当您尝试将数组分配给不是数组的内容时,可能会发生此类错误。
示例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]]
答案 1 :(得分:12)
您需要以这种方式初始化对象:
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"