SWINQ 0.0.3

SWINQ 0.0.3

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布日期最后发布日期2016年5月
SPM支持 SPM

Joey Lai 维护。



SWINQ 0.0.3

SWINQ

简介

SWINQ 是 Swift 2.0 的 LINQ(语言集成查询)。如果您不熟悉 LINQ,它为 .NET 框架提供查询和修改数据的强扩展方法。这些扩展方法不仅使用方便,还使您的代码更易于阅读和理解。

Martin Fowler 撰写的文章“集合管道”提供了关于集成查询的高级信息,并提供了许多在其他语言中如何使用集成查询的具体示例和区别。

安装

手动

如果您不使用 CocoaPods,您可以通过下载最新的 版本 将 SWINQ 手动添加到项目。

用法

firstOrDefault - 如果没有找到元素,根据给定的谓词返回序列中的第一个元素或默认值
[1,2,3,4].firstOrDefault{ (x) in x == 3 } // outputs 3
[1,2,3,4].firstOrDefault{ (x) in x%2 == 0 } // outputs 2
[1,2,3,4].firstOrDefault(0) { (x) in x == 4} //outputs 0
lastOrDefault - 如果没有找到元素,根据给定的谓词返回序列中的最后一个元素或默认值
[1,2,3,4].lastOrDefault{ (x) in x == 3 } // outputs 3
[1,2,3,4].lastOrDefault{ (x) in x%2 == 0 } // outputs 4
[1,2,3,4].lastOrDefault(0) { (x) in x == 5} //outputs 0
all - 根据给定的谓词返回序列中找到的所有元素
[1,2,3,4].all{ (x) in x == 3 } // outputs [3]
[1,2,3,4].all{ (x) in x%2 == 0 } // outputs [2, 4]
[1,2,3,4].all{ (x) in x == 5} //outputs []
select - 将序列中的每个元素转换为新的形式
[1,2,3,4].select{ (x) in "\(x)" } // outputs ["1", "2", "3", "4"]
[1,2,3,4].select{ (x) in x * x } // outputs [1, 4, 9, 16]
selectMany - 扁平化集合
["hello", "world"].selectMany{(x) in Array(x.characters)} // outputs ["h","e","l","o","w","o","r","l","d"]
any - 根据给定的谓词返回序列中是否存在元素的匹配项
[1,2,3,4].any() // outputs true
[1,2,3,4].any{ (x) in x == 3 } // outputs true
[1,2,3,4].any{ (x) in x == 5 } // outputs false
toArray - 从序列创建一个新数组
var original = [1,2,3,4]
var copy = original.toArray()
copy.append(5)

print(original) // outputs [1, 2, 3, 4]
print(copy) // outputs [1, 2, 3, 4, 5]
toDictionary - 从序列创建一个新的字典
["hello","world"].toDictionary { (x) in
    return (key: x.characters.count, value: x)
}

// outputs [5: "hello", 6: "world!"]
take - 从序列开头返回 x 个元素
[1,2,3,4].take(1) // outputs [1]
[1,2,3,4].take(2) // outputs [1, 2]
[1,2,3,4].take(3) // outputs [1, 2, 3]
takeWhile - 返回序列中的元素,直到给定的谓词失败
[1,2,3,4].takeWhile{ (x) in x < 0 } // outputs []
[1,2,3,4].takeWhile{ (x) in x < 3 } // outputs [1, 2]
[1,2,3,4].takeWhile{ (x) in x < 5 } // outputs [1, 2, 3, 4]
skip - 跳过 x 个元素并返回剩余的序列
[1,2,3,4].skip(1) // outputs [2, 3, 4]
[1,2,3,4].skip(2) // outputs [3, 4]
[1,2,3,4].skip(3) // outputs [4]
skipWhile - 继续跳过元素,直到元素匹配给定的谓词
[1,2,3,4].skipWhile{ (x) in x > 1 } // outputs [2, 3, 4]
[1,2,3,4].skipWhile{ (x) in x > 3 } // outputs [4]
[1,2,3,4].skipWhile{ (x) in x > 5 } // outputs []

即将推出...