Last active
August 29, 2015 14:19
-
-
Save ryokosuge/051c32517933b34b3e5d to your computer and use it in GitHub Desktop.
【Swift】Arrayに検索機能を追加する ref: http://qiita.com/ryokosuge/items/c2c1fbeed297db965529
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Array { | |
// 最初に考えついたソースコード | |
func find(includeElement: T -> Bool) -> Int? { | |
for (index, element) in enumerate(self) { | |
if includeElement(element) { | |
return index | |
} | |
} | |
return nil | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
func findAll(includeElement: T -> Bool) -> [(Int, T)] { | |
let seq = zip(0..<self.count, self) | |
return Swift.filter(seq) { includeElement($0.1) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
func find(includeElement: T -> Bool) -> Int? { | |
return Swift.filter(enumerate(self)) { includeElement($0.1) }.first.map { $0.0 } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground | |
class Person { | |
var firstName: String | |
var lastName: String | |
init(firstName: String, lastName: String) { | |
self.firstName = firstName | |
self.lastName = lastName | |
} | |
} | |
var hoge = Person(firstName: "hoge", lastName: "hoge") | |
var fuga = Person(firstName: "fuga", lastName: "fuga") | |
var hogeFuga = Person(firstName: "hoge", lastName: "fuga") | |
var persons:[Person] = [hoge, fuga, hogeFuga] | |
if let hogeIndex = persons.find({ $0 == hoge }) { | |
println(hogeIndex) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment