【问题标题】:Swift function - pass optional objectSwift 函数 - 传递可选对象
【发布时间】:2015-04-27 16:08:37
【问题描述】:

所以我试图在 Swift 中调用函数“submitBoilerPlate”:

var url:String = "https://eamorr.com/ajax/getLatestContent.php"
var params = [
   "hello":"world"
]
submitBoilerPlate(url, _params:params, _button:nil)

这里是对应的函数:

func submitBoilerPlate(_url:String, _params:[String: String!], _button:UIButton?){
    var oldTitle = _button?.titleLabel?.text

    _button?.setTitle("Please wait...", forState: UIControlState.Normal)
    _button?.enabled = false
    //etc.
    ...
}

当我发送一个在我的 xib 上声明的真实 UIButton 时,一切都按预期工作。

但是,我希望能够发送一个“nil”按钮(这个特定的 xib 没有按钮)。

这可能吗?还是我必须创建一个新功能?我正在尝试将代码重复降至最低...

当代码到达 submitBoilerPlate(...) 时,我收到以下运行时错误:

fatal error: can't unsafeBitCast between types of different sizes

【问题讨论】:

    标签: ios function swift parameters


    【解决方案1】:

    你的问题不在于UIButton? 而在于_params:[String: String!],如果你在 submitBoilerPlate 函数下面的某个地方使用它。尝试用_params:[String: String]替换它

    【讨论】:

    • 有效!太感谢了。这只是运行时错误,突出显示了“_button:nil”的“nil”部分。
    • @Eamorr 他解决了你的问题。他应该得到一个公认的答案
    • 如果我有"hello":world.text 会发生什么,其中“world”是 UITextField? world.text 返回字符串! (即不是字符串)
    • 然后声明 _params:[String: String?] 并始终可选地解开其值
    • 非常有用,谢谢。有效。虽然不幸的是,当我将_params:[String String?] 提供给Alamofire.request(.POST, _url, parameters: _params) 时,我得到“字符串?与'AnyObject'不同”
    【解决方案2】:

    将代码粘贴到 Playground 中是帮助自己调试的好方法。我把你的代码带到我自己的操场上,发现以下工作:

    import UIKit
    
    func submitBoilerPlate(_url:String, _params:[String: String!], _button:UIButton?){
        var oldTitle = _button?.titleLabel?.text
    
        _button?.setTitle("Please wait...", forState: UIControlState.Normal)
        _button?.enabled = false
    }
    
    var url:String = "https://eamorr.com/ajax/getLatestContent.php"
    var params:[String: String!] = [
        "hello":"world"
    ]
    submitBoilerPlate(url, params, nil)
    

    注意params 的显式类型,并在submitBoilerPlate 调用中删除了_params_button 错误。

    在没有显式类型的情况下指定 params 会导致编译器无法根据所需的 [String: String!] 参数类型正确对齐您的位。

    _params_button 作为函数调用的一部分实际上是一个错误。当没有空格时,参数没有名称。替代方法的一个示例是:

    func submitBoilerPlate(_url:String, someParams _params:[String: String!], andButton _button:UIButton?) {
      // .. same func body
    }
    
    submitBoilerPlate(url, someParams:params, andButton:nil)
    

    【讨论】:

    • 您好,感谢您的建议。在这里尝试将应用程序从 Objective-C 移植到 Swift...仍在学习曲线中...
    • 我的回答有什么问题没有解决你的问题,我想知道。
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2010-10-16
    • 1970-01-01
    • 2021-09-24
    • 2015-09-18
    • 1970-01-01
    相关资源
    最近更新 更多