iOS中的范围问题

时间:2018-09-20 21:35:16

标签: ios swift

调用以下方法时收到错误消息

select
    i.*,
    case 
      when i.item_type = 'article' then a.title
      when i.item_type = 'post'    then p.post_title
      when i.item_type = 'image'   then
        g.author_first_name + g.author_second_name + g.image_id
    end as item_title
  from item i
  left join article a on i.item_id = a.id
  left join post    p on i.item_id = p.id
  left join image   g on i.item_id = g.id

这是错误消息

  

无法使用参数列表为'Range <_>'的类型调用初始化程序   键入“(范围)”

我将如何更改这些语句以消除此错误,因此转移到pathString.removeSubrange(Range(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7))) XCode 10确实给我带来了困难。

看起来像这样

Swift 4.2

2 个答案:

答案 0 :(得分:0)

您不需要调用Range初始化程序。只需执行以下操作

pathString.removeSubrange(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7))

或此,以提高可读性

let startIndex = pathString.startIndex
let endIndex = pathString.index(pathString.startIndex, offsetBy: 7)
let range = startIndex..<endIndex
pathString.removeSubrange(range)

更新

在评论中,Leo Dabus提出了更好的解决方案

extension StringProtocol where Self: RangeReplaceableCollection {
    mutating func removePrefix(_ prefix: String) {
        if hasPrefix(prefix) {
            removeFirst(prefix.count)
        }
    }
}

添加后,您可以简单地致电

pathString.removePrefix("file://")

答案 1 :(得分:0)

您好,这似乎可以通过以下答案解决: https://stackoverflow.com/a/50719696/7932935

在您的情况下,请替换:

pathString.removeSubrange(Range(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7)))

具有:

pathString.removeSubrange(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7))