所以我有以下功能:
func remoteCall(_url:String, _params:[String: String]?=nil){
...
...
Alamofire.request(.POST, _url, parameters: _params) //requires _params to be of type [String String!]
...
}
如你所见,我可以这样做:
let url = "https://eamorr.com/remote.php"
remoteCall(url) //works great!
或者,我可以这样做:
let url = "https://eamorr.com/remote.php"
let params = [
"email": "eamorr@eamorr.com",
"pword": "secret"
]
remoteCall(url, _params:params) //works great!
然而,我无法做到的是:
let url = "https://eamorr.com/remote.php"
let params = [
"email": email.text, //where "email" is a UITextField
"pword": pword.text //where "pword" is a UITextField
]
remoteCall(url, _params:params) //this doesn't work
我收到此错误:
'String!' is not identical to 'String'
我需要能够容纳所有三种情况(不传递任何内容,传递原始字符串,并传递UITextField值)
不幸的是,如果我尝试更改功能签名(注意'!'在关键字" String"之后)到:
func remoteCall(_url:String, _params:[String: String!]?=nil){
...
...
}
UITextField值有效,传递nil有效,但原始字符串情况在运行时失败。
fatal error: can't unsafeBitCast between types of different sizes
EXC_BAD_INSTRUCTION
我会经常使用这个功能,所以我不想把我的" params"变得凌乱的代码。
我是Swift的新手,一个Objective-C负责人,并试图重新学习所有东西......
我想如果我能以某种方式将任何不正确的[String: String]
整齐地转换为[String: String!]
,而不会打扰任何nil
或[String: String!]
'已经有效了吗?
答案 0 :(得分:3)
我认为这应该有效:
let url = "https://eamorr.com/remote.php"
let params: [String: String] = [ // Note explicitly declared type
"email": email.text, //where "email" is a UITextField
"pword": pword.text //where "pword" is a UITextField
]
remoteCall(url, _params:params)
你的案例中的问题是没有明确的类型声明,Swift会为你推断一个。您创建的词典中的两个值均为String!
类型,与String
的不同。因此错误。如果您明确告诉Swift,params
属于[String: String]
类型应该可以正常工作,因为可以将String!
值分配给String
变量。