ios - 在同一个类中调用枚举函数内部的函数

标签 ios swift

我遇到了一个场景,我必须在 swift 3 中调用枚举函数内的函数。 场景如下:

class SomeViewController: UIViewController {

enum Address {
    case primary
    case secondary

    func getAddress() {

       let closure = { (text: String) in
            showAlert(for: "")
        }
    }
}

func showAlert(for text: String) {
    let alertController = UIAlertController(title: text, message: nil, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title:NSLocalizedString("OK", comment:"OK button title"), style: .cancel, handler: nil))
    present(alertController, animated: true, completion: nil)
}

}

正如您从上面的代码中看到的,我在第 10 行收到错误 (showAlert(for: ""))

错误是:

instance member showAlert cannot be used on type SomeViewController; did you mean to use a value of this type instead?

那么如何从枚举函数中调用函数呢?

最佳答案

替代方法:

您可以使用 SomeViewController静态方法来呈现警报

示例:

static func showAlert(for text: String)
{
    let alertController = UIAlertController(title: text, message: nil, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title:NSLocalizedString("OK", comment:"OK button title"), style: .cancel, handler: nil))
    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}

使用它:

enum Address
{
    case primary
    case secondary

    func getAddress()
    {
        let closure = { (text: String) in
            SomeViewController.showAlert(for: "")
        }
        closure("hello")
    }
}

override func viewDidLoad()
{
    super.viewDidLoad()
    let addr = Address.primary
    addr.getAddress()
}

关于ios - 在同一个类中调用枚举函数内部的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46153335/

相关文章:

ios - 如何使uipicker View 循环?

ios - 将触摸事件(移动/滑动)传递给父级(UITableViewCell),但在当前 View (UITextField)上保留点击事件

ios - 在Ionic 2中禁用iOS中的过度滚动

ios - 一一调用NSURLConnection

ios - IB Designables 无法更新自动布局状态

ios - 如何从我的数组中删除 "..."?

ios - 如何在导航栏或其他屏幕内容上方创建 View ?

添加 subview 时 iOS 奇怪的键盘隐藏行为

ios - 使用 spritekit swift 在 swift 中创建游戏主菜单

swift - 在 Object 子类和它自己的子类上实现 ignoredProperties()