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)
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%.
To determine the percentage, we have to divide the value by the total value and then multiply the resultant by 100.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With