【问题标题】:Usage of String.range in Swift 3.0Swift 3.0 中 String.range 的使用
【发布时间】:2016-08-24 14:24:15
【问题描述】:
let us = "http://example.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.com)", options:.RegularExpressionSearch)
if range != nil {
    let found = us.substringWithRange(range!)
    print("found: \(found)") // found: example
}

这段代码在 Swift 2 中提取了反斜杠和点 com 之间的substring。我搜索了互联网,发现rangeOfString 更改为range()

但我仍然无法使代码在 Swift 3.0 中运行。你能帮帮我吗?

编辑:我正在使用 swift 3 07-25 build。

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

    在 swift 3.0 中 rangeOfString 语法更改为这样。

    let us = "http://example.com"
    let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
    if range != nil {
         let found = us.substring(with: range!)
         print("found: \(found)") // found: example
    }
    

    【讨论】:

    • 它给出了以下错误:1-类型“CompareOptions”(又名“NSString.CompareOptions”)没有成员“RegularExpressionSearch”2-类型“String”的值没有成员“substringWithRange”
    • @H.Cliff 检查下面的答案以获取最新的 SDK
    • @LeoDabus 为此进行了编辑。抱歉忘记为 swift 3 设置它。
    • 欢迎朋友,快乐编码 :) 但我是NDoc
    【解决方案2】:

    在最新的 swift 3.0 中使用 Xcode 8 Beta 6(SDK 的最新更新):

    let us = "http://example.com"
    let range = us.range(of: "(?<=://)[^.]+(?=.com)", options: .regularExpression)
    if range != nil {
        let found = us.substring(with: range!)
        print("found: \(found)") // found: example
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多