Sie können es mit Funktionen höherer Ebene tun, wie folgt aus:
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
}
}
diese Funktion gibt den Index des ersten Spiels, falls vorhanden, oder nil
otherwi se.
Sie können es wie folgt:
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")
}
Schnitt in als Erweiterung zu einer generischen Array ...
Dies kann nun für jede homogene Anordnung von Equatable
Typen verwendet werden.
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
}
}
}
Ich denke, das würde funktionieren, ist aber möglicherweise zu schlau für die Leute zu verstehen. (Es ist sicherlich für mich). Könnten Sie dem bitte einige Kommentare hinzufügen, um zu erklären, was es tut? – Fogmeister
@Fogmeister Sicher! Das ist viel weniger beängstigend als es aussieht, aber im Grunde ersetzt "reduce" eine "for" -Schleife im ursprünglichen Index, während '[String] (data [ind ..
dasblinkenlight
OK, so dass es im Grunde ... bei 0 beginnt. Überprüfen Sie, ob das Subarray bei 0 dem 'part' Parameter entspricht. Wenn es 0 zurückgibt, bis zum Ende. Wenn nicht, gehe zu 1 und überprüfe, ob das Unterfeld bei 1 gleich dem Teileparameter ist und so weiter? – Fogmeister