swift - 如何在 Swift 中更改为某个类型显示的文本表示形式?

标签 swift

如何修改在字符串插值中显示的文本输出?

Printable 协议(protocol)看起来最明显,但它在字符串插值和打印实例时都被忽略了,例如:

struct Point : Printable
{
    var x = 0
    var y = 0

    var description : String {
        return "(\(x), \(y))"
    }

    func toString() -> String {
        return description
    }
}

同样 toString() 约定也没有效果:

var p = Point(x: 10, y: 20)

println(p)                   // V11lldb_expr_05Point (has 2 children)
println("\(p)")              // V11lldb_expr_05Point (has 2 children)
println(p.description)       // (10, 20)
println("\(p.description)")  // (10, 20)

PlayGround 的行为又有所不同,它使用自己的字符串表示结构,即:

p // {x 10, y 20}

有什么方法可以更改实例的显示方式?

最佳答案

swift 2 - 4

总结

符合CustomStringConvertible协议(protocol)并添加description:

var description: String {
    return "description here"
}

例子

您可以创建一些结构:

struct Animal : CustomStringConvertible {
    let type : String

    var description: String {
        return type
    }
}

struct Farm : CustomStringConvertible {
    let name : String
    let animals : [Animal]

    var description: String {
        return "\(name) is a \(self.dynamicType) with \(animals.count) animal(s)."
    }
}

如果你初始化它们:

let oldMajor = Animal(type: "Pig")
let boxer = Animal(type: "Horse")
let muriel = Animal(type: "Goat")

let orwellsFarm = Farm(name: "Animal Farm", animals: [oldMajor, boxer, muriel])

自定义描述将出现在您的 playground 中:

enter image description here

另请参阅 CustomDebugStringConvertible,您可以在调试期间使用它来获得更详细的输出。


使用说明

您可以从任何类型实现此协议(protocol)来初始化String。例如:

enter image description here

出于这个原因,文档说:

Using CustomStringConvertible as a generic constraint, or accessing a conforming type's description directly, is therefore discouraged.

关于swift - 如何在 Swift 中更改为某个类型显示的文本表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24068506/

相关文章:

ios - 找不到带有 Cocoapods 0.37、Swift、框架的 GoogleAnalytics-iOS-SDK 的 header

ios - 使用扩展创建 socket 在 UITableViewCell 中表现得很奇怪

Swift 如何在所有 uiTextfield 上退出第一响应者

ios - Obj-C/Swift 项目中的致命陷阱异常

Swift:子串的简单方法?

ios - 图像仅在 swift 3 中的 Whatsapp 上共享

ios - 如何在 addTarget 的操作中传递参数?

ios - 如何使用 SWrevaelviewController swift 3 将数据从 TableView 的特定行传递到另一个 View Controller

ios - 在 swift 上使用字典时使用未解析的标识符

ios - 将数据从解析 Collection View 传递到新 View