當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift CustomDebugStringConvertible用法及代碼示例

協議

CustomDebugStringConvertible

具有適合調試目的的自定義文本表示的類型。

聲明

protocol CustomDebugStringConvertible

概述

Swift 為任何類型提供了默認的調試文本表示。 String(reflecting:) 初始值設定項和debugPrint(_:) 函數使用該默認表示,用於不提供自己的類型。要自定義該表示,請使您的類型符合CustomDebugStringConvertible 協議。

因為 String(reflecting:) 初始化程序適用於 any 類型的實例,如果傳遞的值符合 CustomDebugStringConvertible ,則返回實例的 debugDescription ,不鼓勵直接訪問類型的 debugDescription 屬性或使用 CustomDebugStringConvertible 作為通用約束.

符合CustomDebugStringConvertible 協議

通過定義 debugDescription 屬性,將 CustomDebugStringConvertible 一致性添加到您的自定義類型。

例如,這個自定義 Point 結構使用標準庫提供的默認表示:


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


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

通過實現debugDescription 屬性添加CustomDebugStringConvertible 一致性後,Point 提供了自己的自定義調試表示。


extension Point: CustomDebugStringConvertible {
    var debugDescription: String {
        return "(\(x), \(y))"
    }
}


print(String(reflecting: 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大神的英文原創作品 CustomDebugStringConvertible。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。