Reputation: 1899
I like to place often used methods in a separate file. I found this answer Use function from one class in another class in Swift but I get errors using it the way I want.
Say i want to create a method called msgBox that pops up an alert box. I created a separate empty Swift file and place this code in it.
import UIKit
class Utils: UIViewController {
class func msgBox (titleStr:String = "Untitled", messageStr:String = "Alert text", buttonStr:String = "Ok") {
var alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: buttonStr, style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
I want to call it like this, but I get errors doing so. Does anyone know what I'm doing wrong?
Utils.msgBox(titleStr: "Hello!", messageStr: "Are you sure?")
Upvotes: 1
Views: 1331
Reputation: 2097
The error is because you are using self
in a class
method. There is no self
instance, in this case.
One thing you could do in this situation is make a class extension. In the following example, you would be able to call the alert
method from any UIViewController
instance:
extension UIViewController {
func alert(title: String?, message: String?, buttonTitle: String = "OK") {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
Notice that I changed a couple names and types, but you can use what you like.
Upvotes: 6