Unify arrays and arrays in Swift

I am very new to Swift and to Apple programming in general. I wrote this code to do a binary search.

func binarySearch<X:Comparable> (needle:X, haystack:[X])->X? {
    if haystack.isEmpty { return nil }
    let mid = haystack.count / 2
    let found = haystack[mid]
    if found == needle {
        return needle
    }
    else if found < needle {
        return binarySearch(needle, haystack[0..<mid])
    }
    else {
        return binarySearch(needle, haystack[mid+1..<haystack.count])
    }
}

and I got syntax errors for recursive calls, because the second parameter is of type ArraySlice<X>instead Array<X>.

I dealt with this by overloading binarySearch with a version that is identical, except that the second parameter is of type ArraySlice<X>.

I think it would be more elegant if everything could be done in one function. Is there a suitable type that combines both Array and ArraySlice? I tried to use ArrayLiteralConvertible<X>, but for some reason does not have a member account. I still have problems finding paths in documents, so I can easily miss out on the option.

? , , , , SO?

+4
2

, Array/ArraySlice . , , . , , , . , :

func bSearch<
  S : Sliceable where S.SubSlice : Sliceable,
  S.SubSlice.Generator.Element == S.Generator.Element,
  S.SubSlice.SubSlice == S.SubSlice,
  S.Generator.Element : Comparable,
  S.Index : IntegerArithmeticType,
  S.Index : IntegerLiteralConvertible,
  S.SubSlice.Index == S.Index
  >(el: S.Generator.Element, list: S) -> S.Generator.Element? {

    if list.isEmpty { return nil }

    let midInd = list.endIndex / 2

    let midEl: S.Generator.Element = list[midInd] // type inference giving me some bugs here

    if midEl == el {
      return el
    }

    return midEl < el ?
      bSearch(el, list: list[midInd+1..<list.endIndex]) :
      bSearch(el, list: list[0..<midInd])
}

Swift 1.2 :

if isEmpty(list) { return nil }

let midInd = list.endIndex / 2

let midEl: S.Generator.Element = list[midInd] // type inference giving me some bugs here

if midEl == el {
  return el
}

return midEl < el ?
  bSearch(el, list[midInd+1..<list.endIndex]) :
  bSearch(el, list[0..<midInd])
+2

, Array , :

func binarySearch<X:Comparable> (needle:X, haystack:[X])->X? {
    if haystack.isEmpty { return nil }
    let mid = haystack.count / 2
    let found = haystack[mid]
    if found == needle {
        return needle
    }
    else if needle < found {
        return binarySearch(needle, Array(haystack[0..<mid]))
    }
    else {
        return binarySearch(needle, Array(haystack[mid+1..<haystack.count]))
    }
}

In addition, your condition should be if needle < found.

+3
source

Source: https://habr.com/ru/post/1598262/


All Articles