像NSObject一样获得描述

时间:2015-02-18 17:20:15

标签: swift debug-symbols println

如果您在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会输出一些调试器模糊,而第二个description会回显NSObject的内容。

那么:有没有一种方法可以像对待println的子类一样处理“普通”类,以便description尊重{{1}}属性的内容?

2 个答案:

答案 0 :(得分:10)

来自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的Playground中不起作用。 它已在Xcode 6.3 beta中修复。从发行说明:

  

•在Playground中添加一致性现在可以按预期工作,...

我在API标头中找不到这个,但似乎NSObject (及其子类)已知符合Printable。 因此,自定义说明适用于您的Test1类。


Swift 2(Xcode 7)中, Printable协议已重命名 到CustomStringConvertible

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

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

答案 1 :(得分:2)

这是因为您正在打印出一个类实例。在swift中,类不是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)

以下是The Swift Programming Language

的引用
  

Swift类不从通用基类继承。给你上课   定义而不指定超类自动成为基类   你可以上课。