Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I declared the % token as a post-fix operator in order to calculate percentage but Xcode reports

`% is not a postfix unary operator` 

My test code below is based on an example found here. I've also checked Apple’s latest documentation for the syntax for Operator Declaration but it gave no clue why Xcode complains.

How do I calculate percentage using % ? And assuming I get it to work, how would I then revert to using % for a modulo operation in another function elsewhere in the same class ?

Can someone offer a working example based on my code in Playground ?

1. % meaning percentage

postfix operator %

var percentage = 25%

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

2. % meaning remainder

let number = 11
let divisor = 7

print(number % divisor)
like image 287
Greg Avatar asked Dec 02 '16 08:12

Greg


People also ask

How do you calculate what percentage was used?

Finding the percentageDivide the number that you want to turn into a percentage by the whole. In this example, you would divide 2 by 5. 2 divided by 5 = 0.4. You would then multiply 0.4 by 100 to get 40, or 40%.

How do I calculate percentage Calcuculate?

To determine the percentage, we have to divide the value by the total value and then multiply the resultant by 100.

What does ~= mean in Swift?

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.


1 Answers

Just move

var percentage = 25%

under

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

Like so

postfix operator %

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

var percentage = 25%

Reason: your code would work in an app, but not in a playground, because a playground interprets the code from top to bottom. It doesn't see the postfix func declaration located below var percentage, so at the point of var percentage it gives you an error, because it doesn't yet know what to do with it.

like image 113
FreeNickname Avatar answered Oct 15 '22 07:10

FreeNickname