Greg
Greg

Reputation: 1842

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

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)

Upvotes: 5

Views: 7827

Answers (3)

FreeNickname
FreeNickname

Reputation: 7814

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.

Upvotes: 7

CZ54
CZ54

Reputation: 5586

This is working for me :

postfix operator %

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


print(25%) // prints 0.25
print(7%5) // prints 2

Upvotes: 0

sabi
sabi

Reputation: 423

postfix operator %

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

var percentage = 25%

8%3

working in playground Xcode 8.1

Upvotes: 0

Related Questions