Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 duplicate question because the accepted answer in my previous post already shows how to do this in Playground. But I have since found that the custom function doesn't work the same way in an Xcode project.

In the template below, I declared the ’operator' at file scope (or at least I believe I did). But when the postfix function is declared, Xcode advises that

    Operator '%' declared in type 'ViewController' must be 'static' 

and offers a fix-it to insert static. With static inserted Xcode then advises

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

Can anyone explain why the % function needs to be static in the Xcode project and what the last error message means in the context of the same line (see below) ? Thanks

Draft 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's the working template based on the accepted answer. I hadn't understood what is meant by declaring the operator at file scope.

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

Building on the accepted answer, custom operator functions grouped in a single file may now be accessed from other files in the same project. To see more visit here.

like image 903
Greg Avatar asked Dec 19 '22 11:12

Greg


1 Answers

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 {

    // ...

}
like image 124
Martin R Avatar answered Mar 16 '23 00:03

Martin R