1

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

0

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.