How to calculate percentage using% as a postfix unary operator in Swift 3 and still use% for modulo?

I declared the % token as a post-fixed operator to calculate the percentage, but Xcode reports

 `% is not a postfix unary operator` 

My test code below is based on an example found here . I also checked the latest Apple documentation for syntax for statement statement , but made it hard to understand why Xcode complains.

How to calculate percentage using % ? And suppose I am working, how would I then return to using % for operations with a module in another function in another place in the same class?

Can anyone suggest a working example based on my code in the Playground?

1.% means percentage

 postfix operator % var percentage = 25% postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } 

2.% means balance

 let number = 11 let divisor = 7 print(number % divisor) 
+5
source share
3 answers

Just move

 var percentage = 25% 

under

 postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } 

In this way

 postfix operator % postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } var percentage = 25% 

Reason : your code will work in the application, but not on the playground, because the playground interprets the code from top to bottom. He does not see the postfix func declaration below the var percentage , so at the point of var percentage it gives you an error, because it still does not know what to do with it.

+6
source

This works for me:

 postfix operator % postfix func % ( percentage: Int) -> Double { return Double(percentage) / 100 } print(25%) // prints 0.25 print(7%5) // prints 2 
0
source
 postfix operator % postfix func % (percentage: Int) -> Double { return (Double(percentage) / 100) } var percentage = 25% 8%3 

works on the Xcode 8.1 playground

0
source

Source: https://habr.com/ru/post/1260690/


All Articles