1
我想检查一个数据实例是否包含特定数据。如何在swift中使用范围3检查数据是否包含另一个使用范围在swift中的数据3
我想检查一个数据实例是否包含特定数据。如何在swift中使用范围3检查数据是否包含另一个使用范围在swift中的数据3
只需使用range(of:)
即可。示例:
let haystack = Data(bytes: [1, 2, 3, 4, 5, 6])
let needle = Data(bytes: [3, 4])
if let range = haystack.range(of: needle) {
print("Found at", range.lowerBound, "..<", range.upperBound)
// Found at 2 ..< 4
}
您可以选择指定搜索范围和/或向后搜索。例如:
let haystack = Data(bytes: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2])
let needle = Data(bytes: [1, 2])
if let range = haystack.range(of: needle, options: .backwards, in: 2..<7) {
print("Found at", range.lowerBound, "..<", range.upperBound)
// Found at 4 ..< 6
}