简体   繁体   English

我们可以使用 Swift 在 Xcode 的操场上扩展一个类吗?

[英]Can we extend a class in playground on Xcode using Swift?

The following code runs perfectly if it is in a standalone command line app:如果它在独立的命令行应用程序中,以下代码可以完美运行:

extension Int {
    func sayHello() {
    println("Hello, I'm \(self)")
    }
}

1.sayHello() 
2.sayHello()

However, in playground, it won't run, and the error is "(2 times)".但是,在操场上,它不会运行,并且错误是“(2 次)”。 Can we not extend a class in playground or how do we do it?我们不能在操场上扩展一个类,或者我们怎么做?

A few corrections:一些更正:

  • "(2 times)" is not an error. “(2 次)”不是错误。 It means your code was executed two times.这意味着你的代码被执行了两次。
  • Int is a struct (value type), not a class Int是一个结构体(值类型),而不是一个类

You can click the eye icon to see the output:您可以单击眼睛图标以查看输出:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM