Member operator '%' must have at least one argument of type 'ViewController’

后端 未结 2 1417
忘了有多久
忘了有多久 2020-12-17 03:56

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

相关标签:
2条回答
  • 2020-12-17 04:42

    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 {
    
        // ...
    
    }
    
    0 讨论(0)
  • 2020-12-17 04:43

    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.

    0 讨论(0)
提交回复
热议问题