加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

统一Swift中的数组和数组切片

发布时间:2020-12-14 04:36:54 所属栏目:百科 来源:网络整理
导读:我是 Swift的新手,也是Apple编程的新手.我写了这段代码来进行二分查找. func binarySearchX:Comparable (needle:X,haystack:[X])-X? { if haystack.isEmpty { return nil } let mid = haystack.count / 2 let found = haystack[mid] if found == needle { re
我是 Swift的新手,也是Apple编程的新手.我写了这段代码来进行二分查找.

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])
    }
}

我在递归调用上遇到语法错误,因为第二个参数的类型是ArraySlice< X>而不是Array< X>.

我通过使用相同的版本重载binarySearch来解决这个问题,除了第二个参数是ArraySlice< X>类型.

如果它可以在一个函数中完成,我认为它会更优雅.是否有合适的类型统一Array和ArraySlice?我尝试使用ArrayLiteralConvertible< X>但由于某些原因,没有计数成员.我在文档中找到自己的方法仍然有点麻烦,所以我可能很容易忽略一个更好的选择.

你能建议一个好方法吗?如果它涉及使用内置类,你可以给我一个关于如何为自己下次找到它的提示,而不是写给SO吗?

解决方法

是的,Array / ArraySlice很烦人.您需要的基本通用要求详见 this问题.但是,为了满足您的要求,不幸的是,您必须获得一些非常可怕的功能签名.但是有可能:

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])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读