【问题标题】:Cannot convert value of type 'Range<Int>' to expected argument type 'Range<Index>' (aka 'Range<String.CharacterView.Index>')无法将类型“Range<Int>”的值转换为预期的参数类型“Range<Index>”(又名“Range<String.CharacterView.Index>”)
【发布时间】:2016-04-20 09:24:03
【问题描述】:

我在这里有一个字符串,我正在尝试对其进行子字符串化。

let desc = "Hello world. Hello World."
var stringRange = 1..<5
desc.substringWithRange(stringRange)

但是 Swift 给了我一个错误。我做错了什么?我正在使用 stringRange 的新符号,因为它不允许我使用旧符号。

【问题讨论】:

    标签: string swift substring


    【解决方案1】:

    您创建的Range 类型不正确,推断为Int。您需要从字符串本身创建范围:

    let desc = "Hello world. Hello World."
    let stringRange = desc.startIndex..<desc.startIndex.advancedBy(5)
    let sub = desc[stringRange]
    

    String 稍微复杂一些。或者,返回NSStringNSRange

    let range = NSMakeRange(0, 5)
    let sub2 = (desc as NSString).substringWithRange(range)
    

    【讨论】:

      【解决方案2】:

      您的1..&lt;5 来自Range&lt;Int&gt; 类型,而substringWithRange 方法需要来自Range&lt;Index&gt; 类型的值

      let desc = "Hello world. Hello World."
      
      var dd = desc.substringWithRange(desc.startIndex..<desc.startIndex.advancedBy(5))
      

      您也可以将advanceBy 申请到desc.startIndex

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-11
        • 2020-02-18
        相关资源
        最近更新 更多