Gre*_*reg 4 xcode ios swift swift3
我正在尝试创建一个简单的Swift 3模板,其中包含一个自定义函数,用于在Xcode应用程序中使用postfix一元运算符计算百分比.这似乎是一个重复的问题,因为我之前的帖子中已接受的答案已经显示了如何在Playground中执行此操作.但我后来发现自定义函数在Xcode项目中的工作方式不同.
在下面的模板中,我宣布了’operator' at file scope(或者至少我相信我做过).但是当声明后缀函数时,Xcode建议这样做
Operator '%' declared in type 'ViewController' must be 'static'
Run Code Online (Sandbox Code Playgroud)
并提供一个修复它插入static.随着static然后插入Xcode的建议
Member operator '%' must have at least one argument of type 'ViewController’.
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么%函数需要static在Xcode项目中以及最后一条错误消息在同一行的上下文中意味着什么(见下文)?谢谢
草稿模板
import UIKit
postfix operator %
class ViewController: UIViewController {
var percentage = Double()
override func viewDidLoad() {
super.viewDidLoad()
percentage = 25%
print(percentage)
}
static postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
}
Run Code Online (Sandbox Code Playgroud)
编辑模板
这是基于接受的答案的工作模板.我没有理解在文件范围内声明操作符的含义.
import UIKit
postfix operator %
postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
class ViewController: UIViewController {
var percentage = Double()
override func viewDidLoad() {
super.viewDidLoad()
percentage = 25%
print(percentage)
}
}
Run Code Online (Sandbox Code Playgroud)
脚注
基于已接受的答案,现在可以从同一项目中的其他文件访问分组在单个文件中的自定义操作员功能.要在这里看到更多访问.
我在文件范围声明了'运营商'
不,你没有.您在定义的范围内定义了它
UIViewController:
postfix operator %
class ViewController: UIViewController {
// ...
static postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
}
Run Code Online (Sandbox Code Playgroud)
一个可以在夫特3定义操作符,如上所述类型的静态成员函数,但是只有当它们采取该类型的至少一个参数.
将声明移动到文件范围以解决问题:
postfix operator %
postfix func % (percentage: Int) -> Double {
return (Double(percentage) / 100)
}
class ViewController: UIViewController {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |