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