我正在学习Apple的新编程语言Swift。我试图使用Swift扩展向printAll
个实例添加一个新方法Array
,当调用它时会打印数组中的所有元素
extention Array {
func printAll() {
for (i, value) in enumerate(self) {
println("\(i+1). \(value)")
}
}
}
// let someAppleProducts = ["iPhone", "iPad", "iWatch", "iMac"]
// someAppleProducts.printAll()
但是我在使用在线编译器runswiftlang.com运行上述脚本时遇到以下错误:
error: cannot invoke 'init' with an argument of type '() -> () -> $T1'
extention Array {
^~~~~~~~
有人可以解释为什么我会收到此错误吗?
但是,将times
方法添加到Int
个实例可以正常运行
extension Int {
func times(task: () -> ()) {
for _ in 0..<self {
task()
}
}
}
3.times({
println("Hello!")
})
打印:
Hello!
Hello!
Hello!
答案 0 :(得分:2)
你拼错了extension
:
extention Array {
应该是
extension Array {
此错误消息具有误导性,我希望它类似于unrecognized token 'extention'
或其他有用的东西!