该库的主要目的是使 Swift 中的数组选择更加清晰和高效。
Solid
文件夹的内容复制到您的项目中。或者
Solid
cocoaapod注意:Swift 2.x 使用 Solid v1.2.3
。Swift 3.0 使用 Solid v3.0
。
let sourceArray = [1, 5, 10, 128, 256, 1024, 2048, 4096, 8000, 8390]
let selection1 = (sourceArray as NSArray)
.beginQuery() // Each query should begin with this call
.skip(2) // Removes first two elements from result selection
// Temporary result: [10, 128, 256, 1024, 2048, 4096, 8000, 8390]
.take(3) // Removes all elements but first three from result selection
// Temporary result: [10, 128, 256]
.endQuery() // This method returns result of selection
// In current case, result is an array equal to [10, 128, 256]
let selection2 = (sourceArray as NSArray)
.beginQuery()
.skip(4) // Temporary result: [256, 1024, 2048, 4096, 8000, 8390]
.take(2) // Temporary result: [256, 1024]
.contains({
// Checks whether at least one element is more than 300
($0 as! Int) > 300
})
.endQuery() // Returns boolean value equal to true
/*
* Let's assume we want to check whether
* all elements of array are bigger than 20
*/
let selection3 = (sourceArray as NSArray)
.beginQuery()
.all({
($0 as! Int) > 20
})
.endQuery() // Returns true
/*
* Another case showing
* how you can process data in the array.
*/
let selection4 = (sourceArray as NSArray)
.beginQuery()
.filter({
// Selects all elements that are bigger than 200
($0 as! Int) > 200
})
.obtain({
// Multiply each number in array by 2 times
($0 as! Int) * 2
})
.sort({
// Sort in descending order
($0 as! Int) > ($1 as! Int)
})
.endQuery() // Returns [16780, 16000, 8192, 4096, 2048, 512]
/*
* You can also select first or last value from the array.
*/
let selection5 = (sourceArray as NSArray)
.beginQuery()
.first()
.endQuery()
let selection6 = (sourceArray as NSArray)
.beginQuery()
.last()
.endQuery()
/*
* Also it's possible to cast result array to required type.
*/
let selection7 = (sourceArray as NSArray)
.beginQuery()
.cast(NSNumber.self)
.endQuery()
Solid
使用 MIT 许可。有关更多信息,请参阅 LICENSE
文件。