Skip to main content
 首页 » 操作系统

ios之Swift 可选参数函数

2024年01月01日53zhujiabin

所以我有以下功能:

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 

我收到这个错误:

“字符串!”与“字符串”不同

我需要能够适应所有三种情况(不传递任何内容、传递原始字符串和传递 UITextField 值)

不幸的是,如果我尝试将函数签名(注意关键字“String”之后的“!”)更改为:

func remoteCall(_url:String, _params:[String: String!]?=nil){ 
   ... 
 
   ... 
} 

UITextField 值有效,传递 nil 有效,但原始字符串情况在运行时失败。

fatal error :无法在不同大小的类型之间进行 unsafeBitCast

EXC_BAD_INSTRUCTION

我会经常使用这个函数,所以我不想用困惑的代码包装我的“params”变量。

我是 Swift 的新手,一个 Objective-C 的头儿,正在尝试重新学习一切...

我想我是否可以在函数内部将任何不正确的 [String: String] 整齐地转换为 [String: String!] 而不会干扰任何 nil 或 [String: String!] 已经可以工作了吗?

请您参考如下方法:

我认为这应该可行:

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 变量。