Aashish Nagar
Aashish Nagar

Reputation: 1227

Check if Data contain another Data using Range in swift 3

I want to check if an instance of Data contain specific data. How to do that using Range in swift 3

Upvotes: 1

Views: 696

Answers (1)

Martin R
Martin R

Reputation: 539795

Just use range(of:). Example:

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
}

You an optionally specify a search range and/or search backwards. Example:

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
}

Upvotes: 2

Related Questions