I am trying to create a simple Swift 3 template with a custom function for calculating percentage using postfix unary operator in an Xcode app. This may seem like a duplicat
I declared the ’operator' at file scope
No, you didn't. You defined it in the scope of the
UIViewController
definition:
postfix operator %
class ViewController: UIViewController {
// ...
static postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
}
One can define operators as static member functions of a type in Swift 3, but only if they take at least one argument of that type.
Move the declaration to the file scope to fix the problem:
postfix operator %
postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
class ViewController: UIViewController {
// ...
}
other alternative if you want to use closures in Swift 3:
import UIKit
typealias Filter = (CIImage) -> CIImage
infix operator >>>
func >>> (filter1: @escaping Filter, filter2: @escaping Filter) -> Filter{
return { image in
filter2( filter1( image))
}
}
class ViewController: UIViewController {
//...
}
Eidhof, Chris; Kugler, Florian; Swierstra, Wouter. Functional Swift: Updated for Swift 3 (Kindle Location 542). GbR Florian Kugler & Chris Eidhof. Kindle Edition.