można to zrobić z funkcji wyższego poziomu, tak:
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
}
}
ta funkcja zwraca indeks pierwszego meczu, jeśli w ogóle, lub nil
otherwi se.
Można go używać w następujący sposób:
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")
}
edycji w jako rozszerzenie ogólnej tablicy ...
To może być teraz używany dla każdej jednorodnej tablicy Equatable
typów.
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
}
}
}
Myślę, że to zadziała, ale jest prawdopodobnie zbyt sprytne, aby ludzie mogli je zrozumieć. (To na pewno jest dla mnie). Czy mógłbyś dodać komentarze do tego, aby wyjaśnić, co robi? – Fogmeister
@Fogmeister Pewnie! Jest to o wiele mniej przerażające niż się wydaje - w zasadzie "zmniejszenie" zastępuje pętlę "for" w początkowym indeksie, natomiast "[String] (data [ind ..
dasblinkenlight
OK, więc w zasadzie robi ... start od 0. Sprawdź, czy podbardzie na 0 jest równa parametrowi 'part'. Jeśli jest to powrót 0 przez cały czas. Jeśli nie, przejdź do 1 i sprawdź, czy podbarwa o wartości 1 jest równa parametrowi części i tak dalej? – Fogmeister