-->

获取描述类似的NSObject(Getting description like NSObject)

2019-10-21 23:20发布

如果您在Playgroud以下

class Test {
  var description:String {
    return "This is Test"
  }
}

class Test1:NSObject {
  override var description:String {
    return "This is Test"
  }
}

let t = Test()
println(t)
let t1 = Test1()
println(t1)

你看到第一println将输出一些调试器的Blurb而第二相呼应的内容description

所以:是有办法,“正常”类将被视为相同的方式的子类NSObject这样println会尊重的内容description的财产?

Answer 1:

println() API文档:

/// Writes the textual representation of `object` and a newline character into
/// the standard output.
///
/// The textual representation is obtained from the `object` using its protocol
/// conformances, in the following order of preference: `Streamable`,
/// `Printable`, `DebugPrintable`.
///
/// Do not overload this function for your type.  Instead, adopt one of the
/// protocols mentioned above.
func println<T>(object: T)

因此,为了得到一个自定义println()表示,你的类必须(例如)采用Printable协议明确:

class Test : Printable {
    var description:String {
        return "This is Test"
    }
}

然而,这并不在Xcode 6.1.1的游乐场工作。 它已被固定在Xcode 6.3测试版。 从发行说明:

•一个游乐场内添加符合,现在可以按预期,...

在API头我找不到这一点,但似乎NSObject (和它的子类)是已知的,以符合Printable 。 因此,自定义说明适用于您Test1类。


夫特2(Xcode的7) Printable协议已被重命名为CustomStringConvertible

class Test : CustomStringConvertible {
    public var description:String {
        return "This is Test"
    }
}

let t = Test()
print(t)
// This is Test


Answer 2:

这是因为你打印出类的一个实例。 在迅速的,一类是不是默认的子类NSObject 。 为了使类的子类NSObject ,你必须指定它就像你做了第二类。 下面是修改后的代码:

class Test {
  var description:String {
    return "This is Test"
  }
}

class Test1:NSObject {
  override var description:String {
    return "This is Test"
  }
}

let t = Test()
println(t.description)
let t1 = Test1()
println(t1)

这里有一个从报价雨燕编程语言

斯威夫特类不从通用基类继承。 您定义的类没有指定一个超自动成为基类,为您建立在。



文章来源: Getting description like NSObject