zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Swift:为 String、Array、Dictionary 添加 isNotEmpty 属性

2023-04-18 13:17:10 时间

前言

想要为 Swift 的 String、Array、Dictionary 这几种常见类型,添加一个 isNotEmpty 属性。

灵感来源于 Dart 中对于判断数组不为空有一个 isNotEmpty 属性:

final array = [1, 2, 3, 4];
print(array.isNotEmpty);

Dart 有,Swift 也可以有啊。

直接明了版本

最直接明了的版本当然就是分别给 String、Array、Dictionary 写分类,在分类中添加一个只读计算属性 isNotEmpty 即可。

String+Extension:

extension String {
    var isNotEmpty: Bool { !isEmpty }
}

Array+Extension:

extension Array {
    var isNotEmpty: Bool { !isEmpty }
}

Dictionary+Extension:

extension Dictionary {
    var isNotEmpty: Bool { !isEmpty }
}

上面 3 个分类,分别实现了 String、Array、Dictionary 三个常用类型的 isNotEmpty。

但是!!!

你要了解到,有 isEmpty 属性的类型远不止以上三种类型,难道之后有需求对其他带有 isEmpty 属性的类型添加 isNotEmpty 属性,我都要来写一个分类?

这很明显的是没有看透 String、Array、Dictionary 这些类型的背后,是由什么在支撑着它们可以拥有 isEmpty 属性。

更本质的版本

滴水穿石非一日之功,冰冻三尺非一日之寒。

我想说的是入门的时候都会选择直接了当的写法,不过当在反反复复 CV 代码的时候,我们需要的是观察,归纳,抽离,封装。

上图不知道大家注意到没有:

  • Dictionary → Collection
  • Array → MutableCollection → Collection

Array 与 Dictionary 都遵守了 Collection 协议,那么这个 isEmpyt 属性会不会就存在于 Collection 协议中呢?

带着这个疑问,我们去看看 Collection 协议就知道了:

extension Collection {
    /// A Boolean value indicating whether the collection is empty.
    ///
    /// When you need to check whether your collection is empty, use the
    /// `isEmpty` property instead of checking that the `count` property is
    /// equal to zero. For collections that don't conform to
    /// `RandomAccessCollection`, accessing the `count` property iterates
    /// through the elements of the collection.
    ///
    ///     let horseName = "Silver"
    ///     if horseName.isEmpty {
    ///         print("My horse has no name.")
    ///     } else {
    ///         print("Hi ho, (horseName)!")
    ///     }
    ///     // Prints "Hi ho, Silver!")
    ///
    /// - Complexity: O(1)
    @inlinable public var isEmpty: Bool { get }
}

上面这段代码,摘自于 Swift 中的 Collection 源码,如果仔细看代码注释,会发现,举例说明中是以 String 的 isEmpty 进行的,这也说明 String 类型直接或者间距都遵守 Collection 协议的。

这么一来就好办了,我只需要在 Collection 协议的分类中,添加一个 isNotEmpty 属性即可:

extension Collection {
    /// 判断集合非空
    public var isNotEmpty: Bool {
        return !isEmpty
    }
}

使用:

let array = []
print(array.isNotEmpty)

let dict = [:]
print(dict.isNotEmpty)

let string = ""
print(string.isNotEmpty)

以上代码均可以点出 isNotEmpty,并打印 true,效果符合预期。

Swift 里集合类型协议的关系[1]

总结

代码总是搬运不完的啦,但是读懂代码,观察代码我们都是可以的啦,只不过这其中需要我们多写一些代码,甚至多走一点弯路。

我们下期见。

参考资料

[1]

Swift 里集合类型协议的关系: https://www.cnblogs.com/huahuahu/p/Swift-li-ji-he-lei-xing-xie-yi-de-guan-xi.html