how to pass in an object from an array of objects in a binary search on swift? I have the following:
func binarySearchPrefix(array: [String], target:
String) -> Bool {
var left = 0
var right = array.count
- 1
while (left <= right)
{
let mid = (left + right) / 2
let value = array[mid]
if (value.hasPrefix(target)) {
return true
}
if (value < target) {
left = mid + 1
}
if (value > target) {
right = mid - 1
}
}
return false
}
how can i call this using object
struct someObject {
var value: String = "hello"
var key: String = "hello"
}
var Thing = someObject()
var Thing1 = someObject()
var Thing2 = someObject()
var arrayOfObjects [Thing, Thing1, Thing2,]
I want to call the function and pass in Thing.value and Thing.key into the binary search, but from the arrayofObjects, not directly. How would I do it?
I tried
binarySearchPrefix(array: arrayOfObjects, target: "hello" ) but it says it's looking for a String, it seems like I need to modify my binary search. Any ideas?
Hi first it is not a question of Algebra.Its Computer Science.
You are trying it incorrectly.In your function binarySearchPrefix the parameter is array of String( func binarySearchPrefix(array: [String], target: String) -> Bool).
But when you call this function you pass an array of object.
You have two option
1. By Modify func as:
func binarySearchPrefix(array: [someObject], target: String) -> Bool
In this case you also need to change logic of function.
2. in function call pass array of String.
var arrayOfObjects = [Thing.value, Thing1.value, Thing2.value]
and pass it to function.
Please Thumbs up.
Get Answers For Free
Most questions answered within 1 hours.