我遇到了一个场景,我必须在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: ""))
错误是:
实例成员showAlert不能用于SomeViewController类型;你的意思是使用这种类型的值吗?
如何从枚举函数中调用函数呢?
答案 0 :(得分:3)
替代方法:
您可以使用static method
SomeViewController
来展示alert
。
<强> 实施例 强>
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()
}
答案 1 :(得分:1)
enum
不知道实例,因此无法访问其成员。处理这种情况的一种方法是告知客户enum
出现问题。
class SomeViewController: UIViewController {
enum Address {
case primary
case secondary
func getAddress() -> String? {
//allGood == whatever your logic is to consider a valid address
if allGood {
return "theAddress"
} else {
return nil;
}
}
}
func funcThatUsesAddress() {
let address = Address.primary
guard let addressString = address.getAddress() else {
showAlert(for: "")
return
}
// use your valid addressString here
print(addressString)
}
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)
}
}