一、前言

先看一下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"
*/

如果想了解更多内容,可以参见专栏 《ios开发你需要知道的》

Swift CustomStringConvertible 协议的使用的更多相关文章

  1. Swift泛型协议的N种用法

    They said "you should learn a new language every year," so I  learned Swift. Now  I  learn ...

  2. 窥探Swift之协议(Protocol)和委托代理(Delegate)回调的使用

    协议与委托代理回调在之前的博客中也是经常提到和用到的在<Objective-C中的委托(代理)模式>和<iOS开发之窥探UICollectionViewController(四) - ...

  3. Swift利用协议优化NSNotificationCenter

    NSNotificationCenter存在的问题 通知没有统一的命名格式 对于通知的命名没有强制的要求,一个项目里可能有多种不同的命名规则.比如: 1 2 3 4 5 6 class Barista ...

  4. swift 当协议遇见了泛型

    由于泛型比较简单,并没有单独拿出来介绍!我们在定义函数的时候,有时候只是由于参数或者返回值类型不同,而具体的实现过程是一模一样的,这个时候我们就可以定义泛型函数而使可以传入不同的参数类型: func ...

  5. 利用Swift之协议语法实现页面间的传值功能

    随着Swift 新开发语言的发布,又随着Xcode6.0.1的正式发布,利用swift编写iOS代码迫在眉睫,笔者在使用Objective-C开发近三年以来,对这种优雅的语法深感赞叹,下面我将对比式的 ...

  6. swift 用协议实现代理传值功能

    1.功能简介 RootViewController中用个lable和一个按钮,点击按钮跳转到模态窗口.在模态窗口中有个TextField和一个按钮,输入文字点击关闭模态按钮后跳转到RootViewCo ...

  7. iOS oc和swift中协议的使用

    创建一个空的工程 在工程中我们新建一个类 继承与NSObject 定义一个协议‘ @protocol UpdateAlertDelegate <NSObject> //这里的红色字体就是我 ...

  8. Swift学习——A Swift Tour 协议和扩展

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhenyu5211314/article/details/28854395 Protocols an ...

  9. swift面向协议编程

    https://www.technotification.com/2018/08/protocol-oriented-programming-swift.html https://www.toptal ...

  10. swift开发之--Protocol(协议)

    使用object-c语言的同学们肯定对协议都不陌生,但在swift中苹果将protocol这种语法发扬的更加深入和彻底. Swift中的protocol不仅能定义方法还能定义属性,配合extensio ...

随机推荐

  1. SpringMvc配置和原理

    运行原理 DispatcherServlet通过HandlerMapping在MVC的容器中找到处理请求的Controller,将请求提交给Controller,Controller对象调用业务层接口 ...

  2. [Leetcode 111]二叉树的最短深度 BFS/DFS

    题目 给定二叉树,求最短路径包含的节点个数 https://leetcode.com/problems/minimum-depth-of-binary-tree/ Given a binary tre ...

  3. 【原创】SeetaFace2 Android编译

    SeetaFace2 github上有很完整的编译说明,但是自己编译过程中还是遇到了一点小问题.记录一下 编译环境: wsl ubuntu 20.04 执行编译命令 cmake .. -DCMAKE_ ...

  4. spacy

    官方文档: https://spacy.io/api Spacy功能简介 可以用于进行分词,命名实体识别,词性识别等等,但是首先需要下载预训练模型 pip install --user spacy p ...

  5. python学习记录(五)-文件操作

    open()参数说明 ''' 参数1:路径 ./当前目录 ../上一级目录 参数2: 基础模式:w r x a w:写入,不存在则创建,存在则打开,清空文件内容,光标指向最前面 r:只读,不存在则报错 ...

  6. Linux挂载U盘报错:mount: unknown filesystem type 'ntfs'

    原因:由于Linux上无法识别NTFS格式的分区的原因 解决方法:安装 ntfs-3g 1.下载:wget https://tuxera.com/opensource/ntfs-3g_ntfsprog ...

  7. 什么是互联网控制消息协议ICMP 以及如何作为网络分析利器

    什么是互联网控制消息协议(ICMP) Internet控制消息协议(ICMP)是网络设备用来诊断网络通信问题的网络层协议.ICMP主要用于确定数据是否及时到达其预期目的地.通常,ICMP协议用于网络设 ...

  8. Apache与tomcat区别--转水漫金山

    Apache与Tomcat都是Apache开源组织开发的用于处理HTTP服务的项目,两者都是免费的,都可以做为独立的Web服务器运行.Apache是Web服务器而Tomcat是Java应用服务器 Ap ...

  9. MySQL学习(七)varchar和char区别

    varchar:用于存储可变长字符串,是最常见的字符串数据类型.比定长类型更节省空间,因为它仅使用必要的空间.varchar需要使用1或2个额外字节记录字符串的长度:如果列的最大长度小于或等于255字 ...

  10. fastposter v2.13.0 一分钟完成开发海报 [云服务来袭]

    fastposter v2.13.0 一分钟完成开发海报 [云服务来袭] fastposter海报生成器是一款快速开发海报的工具.只需上传一张背景图,在对应的位置放上组件(文字.图片.二维.头像)即可 ...