利用 where 条件给特定的集合类型增加扩展方法

有时我们需要给特定的集合类型增加一个扩展方法,例如给 Array<String> 增加一个 isStringElement 属性,或者增加一个 random 方法来实现 String 的随机乱序,这时可以使用 where 子句, 限制 Element 为 String,例如:

extension Array where Element == String {
    var isStringArray:Bool {
        return true
    }
    func random() -> Array<String> {
        var result = self
        for index in 0..<result.count {
            let newIndex = Int(arc4random_uniform(UInt32(result.count-index))) + index
            if index != newIndex {
                result.swapAt(index, newIndex)
            }
        }
        return result
    }
}
let isString = ["he", "she", "it"].isStringArray // true
let randomArray = ["he", "she", "it"].random() // 随机出现["he", "it", "she"]

That's all ~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。