标签:
let array = Array(5...25) var anotherArray = [Int]() for i in array{ if i > 20{ anotherArray.append(i) } } print(anotherArray) //[21, 22, 23, 24, 25]
let secondArray = array.filter { (i: Int) -> Bool in return i > 20 //注意:根据需求在闭包内进行相应的操作。 } print(secondArray) //[21, 22, 23, 24, 25]
let thirdArray = array.filter ({$0 > 20}) print(thirdArray) // [21, 22, 23, 24, 25]
var people = [ ["First": "JohnMusk", "Last": "Doe"], ["First": "Steve", "Last": "Jobs"], ["First": "Elon", "Last": "Musk"] ] var searchText = "Musk" var searchResults = people.filter{ var firstName = $0["First"]!.lowercaseString var lastName = $0["Last"]!.lowercaseString return firstName.rangeOfString(searchText.lowercaseString) != nil || lastName.rangeOfString(searchText.lowercaseString) != nil } print(searchResults) //[["First": "JohnMusk", "Last": "Doe"], ["First": "Elon", "Last": "Musk"]]
let searchResult = people.filter{ var found = false let searText = "Musk" for str in $0.values { found = str.lowercaseString.rangeOfString(searText.lowercaseString) != nil if found { break } } return found } print(searchResult) //[["First": "JohnMusk", "Last": "Doe"], ["First": "Elon", "Last": "Musk"]]当然,我们也可以使用谓词进行过滤操作
let firstNameQuery = "jo" let lastNameQuery = "mus" let predicate = NSPredicate(format: "%K CONTAINS[cd] %@ OR %K CONTAINS[cd] %@", "First", firstNameQuery, "Last", lastNameQuery) let sorted = people.filter({ return predicate.evaluateWithObject($0) }) print(sorted) //[["First": "JohnMusk", "Last": "Doe"], ["First": "Elon", "Last": "Musk"]]
标签:
原文地址:http://blog.csdn.net/longshihua/article/details/51363482