如何在Swift 3中使用%作为后缀一元运算符来计算百分比,并且仍然能够对模数使用%? [英] How to calculate percentage using % as a postfix unary operator in Swift 3 and still be able to use % for modulo?

查看:38
本文介绍了如何在Swift 3中使用%作为后缀一元运算符来计算百分比,并且仍然能够对模数使用%?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将令牌声明为后缀运算符,以便计算百分比,但Xcode报告

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

`% is not a postfix unary operator` 

下面的测试代码 是基于此处.我还检查了Apple的最新文档,以获取

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 ?

有人可以根据我在Playground中的代码提供一个可行的示例吗?

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

1.%表示百分比

postfix operator %

var percentage = 25%

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

2.%表示剩余

let number = 11
let divisor = 7

print(number % divisor)

推荐答案

只需移动

var percentage = 25%

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

像这样

postfix operator %

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

var percentage = 25%

原因:您的代码可以在应用中运行,但不能在游乐场中使用,因为游乐场会从上到下解释代码.它没有在 var percent 下找到 postfix func 声明,因此在 var percent 的位置,它会给您一个错误,因为它尚不知道该怎么办.

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.

这篇关于如何在Swift 3中使用%作为后缀一元运算符来计算百分比,并且仍然能够对模数使用%?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆