双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

Swift CustomStringConvertible 协议的使用

ReyZhang ReyZhang 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

一、前言

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

相关推荐

swift-Stringfication让所有对象变成字符串

Stringfication:让所有对象变成字符串

weixin_39840914

objccn-Swift 进阶

objccn 出版的swift 进阶。 讲述了swift 的高级用法。

wangyunico88

Swift中用到extension的一些基本的扩展功能讲解

主要介绍了Swift的一些基本的扩展功能,即extension关键字的使用,需要的朋友可以参考下

weixin_38518518

Swift颜色生成器RandomColorSwift.zip

RandomColorSwift 是从 randomColor.js 移植过来的 Swift 颜色生成器,非常迷人。代码示例:import RandomColor // Returns a UIColor or NSColor object for an attractive color let color = randomColor() // Returns an array of ten green colors let greenColors = randomColorsCount(10, hue: .Green) // Returns a color for light blue let lightBlurColor = randomColor(hue: .Blue, luminosity: .Light) // Returns a color for a 'truly random' color let randomColor = randomColor(hue: .Random, luminosity: .Random) // Returns an array of ten dark pink colors let darkPinkColors = randomColorsCount(10, hue: .Pink, luminosity: .Dark) // Returns an array of twenty colors at hue of 120 let colors = randomColorsCount(20, hue: .Value(120), luminosity: .Random)

weixin_39840515

java种菜源码-swift-linq-examples:C#的101个LINQ示例转换为Swift

java种菜源码Swift 3 中的 101 个 LINQ 示例 将端口重写为 . 将 Swift 与其他编写的 LINQ 示例进行比较: 如果您正在寻找一种用于在 iOS 或 OSX Swift 3.0 应用程序中使用 .NET Web 服务的简单类型 API,请查看 ServiceStack 的 . 运行示例 您可以通过评论您不感兴趣的部分来选择运行特定示例。 要查看所有示例的完整输出,请在本地运行 XCode 项目。 内容 下面的示例反映了 C# LINQ 示例布局,顶级 Swift 方法的名称与其对应的 C# 示例相匹配。 / / / / / / / / / / / / / / 并排 - C# LINQ 与 Swift 为了进行并排比较,原始C#源代码显示在等效的Swift翻译之上。 输出显示了运行Swift示例的控制台输出。 以...结尾的输出说明仅显示部分响应。 使用的 C# ObjectDumper 实用程序可从 MSDN 下载 - 与许多支持函数式风格的语言不同,Swift 默认没有内置许多类似 LINQ 的实用程序,但由于 Swift 具有高度可扩展性,因此可以轻松地

weixin_38727567
评论
收藏 已收藏
分享
返回顶部
ReyZhang
ReyZhang 新星创作者: 移动开发技术领域 新星创作者: 移动开发技术领域
Rey的移动开发社区 420 成员 23 内容