大佬教程收集整理的这篇文章主要介绍了arrays – Array包含一个完整的子数组,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
let mainArray = ["hello","world","it's","a","beautiful","day"] contains(mainArray,["world","it's"]) // would return true contains(mainArray,"it"]) // would return false contains(mainArray,"a"]) // would return false - not adjacent in mainArray
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 } }
您可以按如下方式使用它:
let mainArray = ["hello","day"] if let index = indexOf(mainArray,"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 } } }
以上是大佬教程为你收集整理的arrays – Array包含一个完整的子数组全部内容,希望文章能够帮你解决arrays – Array包含一个完整的子数组所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。