このようにあなたは、より高いレベルの機能でそれを行うことができます。
func indexOf(data:[String], _ part:[String]) -> Int? {
// This is to prevent construction of a range from zero to negative
if part.count > data.count {
return nil
}
// The index of the match could not exceed data.count-part.count
return (0...data.count-part.count).indexOf {ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[String](data[ind..<ind+part.count]) == part
}
}
この機能があれば、最初のマッチのインデックスを返し、またはnil
otherwi se。
次のようにあなたはそれを使用することができます。一般的な配列への拡張としてで
let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]
if let index = indexOf(mainArray, ["world", "it's"]) {
print("Found match at \(index)")
} else {
print("No match")
}
編集...
これは今Equatable
種類のいずれかの均質な配列のために使用することができます。
extension Array where Element : Equatable {
func indexOfContiguous(subArray:[Element]) -> Int? {
// This is to prevent construction of a range from zero to negative
if subArray.count > self.count {
return nil
}
// The index of the match could not exceed data.count-part.count
return (0...self.count-subArray.count).indexOf { ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[Element](self[ind..<ind+subArray.count]) == subArray
}
}
}
これはうまくいくと思いますが、人々が理解するにはあまりにも賢いかもしれません。 (それは確かに私のためです)。あなたはそれが何をしているのかを説明するためにこれにいくつかのコメントを追加することができますか? – Fogmeister
@Fogmeisterよろしく!基本的には、初期インデックスの "for"ループを "reduce"に置き換え、 '[String](data [ind ..
dasblinkenlight
OKですので、基本的には0で始まります。0の部分配列が 'part'パラメータと等しいことを確認してください。それがすべて0を返すならば。 1になっていない場合、部分配列が1であることを部分パラメータと同じようにチェックするなどですか? – Fogmeister