Swift writing a function that takes self as an input

廉价感情. 提交于 2019-12-02 09:58:00

What you need is to extend UIViewController this way you don't need to pass any view controller as parameter and self will always be a view controller. And make sure you call the view controller's present method present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) from the main thread:

extension UIViewController {
   enum Message: CustomStringConvertible  {
        case missingTitle, chooseProject
        var description: String {
            let message: String
            switch self {
            case .missingTitle: message = "sorry but you must give the project a title and description"
            case .chooseProject: message = "sorry but you need to choose a type of project"
            }
            return message
        }
    }
    func alertSCFlag(title: String = "Not Finished", message: Message) {
        let alert = UIAlertController(title: title, message: message.description, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        DispatchQueue.main.async {
            self.present(alert, animated: true)
        }
    }
}

Usage:

let vc = UIViewController()
vc.alertSCFlag(message: .chooseProject)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!