当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift CustomStringConvertible用法及代码示例


协议

CustomStringConvertible

具有自定义文本表示的类型。

声明

protocol CustomStringConvertible

概述

符合 CustomStringConvertible 协议的类型可以提供自己的表示形式,以便在将实例转换为字符串时使用。 String(describing:) 初始化程序是将any 类型的实例转换为字符串的首选方法。如果传递的实例符合 CustomStringConvertible ,则 String(describing:) 初始化程序和 print(_:) 函数使用实例的自定义 description 属性。

不鼓励直接访问类型的 description 属性或使用 CustomStringConvertible 作为通用约束。

符合CustomStringConvertible 协议

通过定义 description 属性,将 CustomStringConvertible 一致性添加到您的自定义类型。

例如,这个自定义 Point 结构使用标准库提供的默认表示:


struct Point {
    let x: Int, y: Int
}


let p = Point(x: 21, y: 30)
print(p)
// Prints "Point(x: 21, y: 30)"

在实现description 属性并声明CustomStringConvertible 一致性之后,Point 类型提供了自己的自定义表示。


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


print(p)
// Prints "(21, 30)"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 CustomStringConvertible。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。