ios - Swift 可选参数函数

标签 ios xcode function swift option-type

所以我有以下功能:

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

关于ios - Swift 可选参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726974/

相关文章:

swift - 按下时更改 UICollectionView 单元格大小 - Xcode Swift

c++ - 为什么要使用 const 成员函数?

c++ - 无法从 main 引用 .cpp 和 .h 文件中的函数。 C++

objective-c - 如何使用 objective-c 分割或切碎音频文件

ios - 有没有办法让 CoreData 与服务器 API 保持同步,即使应用程序处于后台/暂停/终止状态?

iphone - 如何根据事件配置获得条件代码?

function - 如何使用VB6传递函数参数?

ios - 如何运行导致框架运行时错误的 iOS 应用程序 "code signature invalid"

iphone - 有没有更新的用于使用最新 ffmpeg 的 iPad/iPhone 视频流的 http 分段器?

ios - 启用/禁用 UIButton 取决于 UITextField 中文本的长度