gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:28 25 4
gpt4 key购买 nike

我遇到了一个场景,我必须在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com