Swift CustomStringConvertible 协议的使用

一、前言

先看一下Swift标准库中对CustomStringConvertible协议的定义

public protocol CustomStringConvertible {
    /// A textual representation of this instance.
    ///
    /// Calling this property directly is discouraged. Instead, convert an
    /// instance of any type to a string by using the `String(describing:)`
    /// initializer. This initializer works with any type, and uses the custom
    /// `description` property for types that conform to
    /// `CustomStringConvertible`:
    ///
    ///    struct Point: CustomStringConvertible {
    ///        let x: Int, y: Int
    ///
    ///        var description: String {
    ///            return "(\(x), \(y))"
    ///        }
    ///    }
    ///
    ///    let p = Point(x: 21, y: 30)
    ///    let s = String(describing: p)
    ///    print(s)
    ///    // Prints "(21, 30)"
    ///
    /// The conversion of `p` to a string in the assignment to `s` uses the
    /// `Point` type's `description` property.
    var description: String { get }
}

从声明中我们可以看到协议中只包含了一个 description的只读属性 ,而且通过协议命名也可以窥探到它的作用 Custom+String+Convertible (所作用的类型去自定义String的转换)

实现CustomStringConvertible协议类似于在Objective-C中重写description方法, 可用于:

  • 自定义作用类型的print输出
  • 作用的类型可自定义转换成String

如标准库中给的示例,拿出来分析一下:

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

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

let p = Point(x: 21, y: 30)
let s = String(describing: p)
print(s)


// Prints "(21, 30)"

上例中结构体Point 实现了CustomStringConvertible协议, 完成了description属性的实现, 返回自定义字符串 "((x), (y))"。 接着使用String类型的 String(describing: p ) 初始化方法完成了 Point结构体转成指定String类型格式的转换。

通过上面的介绍,我们基本上了解了CustomStringConvertible协议的用法, 接下来介绍几种使用场景。

首先要知道的是 -- 在Swift中可以实现协议的类型有 结构体、 、 枚举。 也就是说只有结构体、 类、 枚举等类型都可以实现CustomStringConvertible协议

二、使用场景

1. 整型类型的枚举使用

enum AudioStatus: Int {
	case stopped = 0, playing, recording, interruptionPlaying, interruptionRecording
}

如果在使用枚举时,除了需要访问枚举的整型值外,还需要可以方便的输出每个枚举对应的字符串类型的状态。 那么在这种场景下,通过extension扩展枚举,并实现CustomStringConvertible协议将会很合适

extension AudioStatus : CustomStringConvertible {
    
    var description: String {
        switch self  {
        case .stopped:
            return "Audio: Stopped"
        case .playing:
            return "Audio: Playing"
        case .recording:
            return "Audio: Recording"
        case .interruptionPlaying:
            return "Audio: interruptionPlaying"
        case .interruptionRecording:
            return "Audio: interruptionRecording"
        }
    }
}

使用:

let status:AudioStatus = .stopped
let audioName = String(describing:status)  //取整型枚举对应的 字符串值
print(“audioName:\(audioName)”)

2. Class类型的使用

定义一个类的话, 当我们使用print 时候并不会输出类中的变量

class Wheel {
    var spokes: Int = 0
    var diameter: Double = 0.0
    
    init(spokes:Int = 32,diameter:Double = 26.0) {
        self.spokes = spokes
        self.diameter = diameter
    }
    
    func removeSpokes() {
        spokes = spokes > 0 ? spokes-- : spokes
    }
}

var wheel = Wheel(spokes: 36,diameter: 29)
print(wheel)
/**
 *  "Wheel\n"
 */

如果想要改变 print 的输出结果,我们需要让类遵守这个协议,最好用 extension扩展 

extension Wheel: CustomStringConvertible {
    var description: String {
        return "wheel has \(spokes) spokes"
    }
}
var wheel = Wheel(spokes: 36,diameter: 29)
print(wheel)
/**
 *  "wheel has 36 spokes\n"
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Swift 中,可以使用协议来限制属性的特定实现。下面是一些示例: 1. 只读属性协议 我们可以定义一个只读属性协议,让遵循该协议的类型只能实现只读属性: ``` protocol ReadOnlyProperty { var value: Int { get } } struct MyStruct: ReadOnlyProperty { let value: Int } ``` 在上面的代码中,`ReadOnlyProperty` 协议定义了一个只读属性 `value`。然后,我们定义了一个结构体 `MyStruct`,该结构体遵循 `ReadOnlyProperty` 协议,并实现了只读属性 `value`。 2. 可写属性协议 我们可以定义一个可写属性协议,让遵循该协议的类型只能实现可写属性: ``` protocol WritableProperty { var value: Int { get set } } struct MyStruct: WritableProperty { var value: Int } ``` 在上面的代码中,`WritableProperty` 协议定义了一个可读写属性 `value`。然后,我们定义了一个结构体 `MyStruct`,该结构体遵循 `WritableProperty` 协议,并实现了可写属性 `value`。 3. 只写属性协议 我们可以定义一个只写属性协议,让遵循该协议的类型只能实现只写属性: ``` protocol WriteOnlyProperty { var value: Int { set } } class MyClass: WriteOnlyProperty { var value: Int = 0 } ``` 在上面的代码中,`WriteOnlyProperty` 协议定义了一个只写属性 `value`。然后,我们定义了一个类 `MyClass`,该类遵循 `WriteOnlyProperty` 协议,并实现了只写属性 `value`。 通过以上示例,我们可以看到如何使用协议来限制属性的特定实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2301_76429513

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值