I am trying to create a simple Swift 3 template with a user-defined function for calculating a percentage using a postfix unary operator in an Xcode application. This may seem like a duplicate question, because the accepted answer in my previous post already shows how to do this on the Playground. But since then, I have discovered that a user-defined function does not work the same in an Xcode project.
In the template below, I declared 'operator' at file scope (or at least I think I did). But when the postfix function is declared, Xcode reports that
Operator '%' declared in type 'ViewController' must be 'static'
and offers a fix for entering static . Using static inserted Xcode then advise
Member operator '%' must have at least one argument of type 'ViewController'.
Can someone explain why the % function should be static in the Xcode project and what the last error message means in the context of the same line (see below)? Thanks
Project template
import UIKit postfix operator % class ViewController: UIViewController { var percentage = Double() override func viewDidLoad() { super.viewDidLoad() percentage = 25% print(percentage) } static postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } }
EDITED Template
Here the work pattern is based on the accepted answer. I did not understand what is meant by the declaration of the operator in the file area.
import UIKit postfix operator % postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } class ViewController: UIViewController { var percentage = Double() override func viewDidLoad() { super.viewDidLoad() percentage = 25% print(percentage) } }
FOOTNOTE
Based on the accepted answer, user-defined operator functions grouped into one file can now be accessed from other files in the same project. To learn more, visit here .
source share