【问题标题】:Swift 5.1 Substring Issue [duplicate]Swift 5.1 子字符串问题 [重复]
【发布时间】:2020-02-10 08:50:13
【问题描述】:

我是 Swift 的新手。我使用 Swift 5.1 我想从字符串中获取子字符串,但我做不到。 我已经尝试了几种解决方案(herehere),但这些对我不起作用。

我试过这样:

func substring(x : Int, y : Int, s : String) -> String {
  let start = s.index(s.startIndex, offsetBy: x);
  let end   = s.index(s.startIndex, offsetBy: y);
  return s[start..<end];
}

print(substring(x: 0, y: 2, s: "abcde"))

/tmp/306AE87E-57C7-417C-B2EF-313A921E75B9.BuUdsc/main.swift:6:11: 错误:下标 'subscript(_:)' 需要类型 'String.Index' 和 'Int' 等价 return s[start..(bounds: R) -> String where R : RangeExpression, R.Bound == Int { get } ^

非常感谢您的帮助。谢谢。

【问题讨论】:

标签: substring swift5.1


【解决方案1】:

这又是那些令人困惑的错误消息之一,它并没有告诉您您是否真的做错了。

你应该这样做:

return String(s[start..<end])

这是因为接受Range&lt;String.Index&gt;的下标实际上返回了Substring,但是你的方法返回了String,所以你必须在返回之前进行转换。

推测输出错误信息的原因:

看到该方法返回一个String,Swift 编译器试图找到一个返回一个String 的下标,以及它如何找到一个(我找不到),但重载仅适用于具有Index 关联类型为Int

【讨论】:

【解决方案2】:

您的代码大部分都很好,但 Swift 搞砸了错误消息。我用 Swift 5.2 更好的错误诊断在 Xcode 11.4 beta 中尝试了你的代码,它抱怨返回类型 String 不正确,因为 s[start..&lt;end] 给你一个 Substring。您可以更改返回类型:

func substring(x : Int, y : Int, s : String) -> Substring {
  let start = s.index(s.startIndex, offsetBy: x)
  let end   = s.index(s.startIndex, offsetBy: y)
  return s[start..<end]
}

print(substring(x: 0, y: 2, s: "abcde"))

或将子字符串转换为字符串:

func substring(x : Int, y : Int, s : String) -> String {
  let start = s.index(s.startIndex, offsetBy: x)
  let end   = s.index(s.startIndex, offsetBy: y)
  return String(s[start..<end])
}

print(substring(x: 0, y: 2, s: "abcde"))

旁注:; 在 Swift 中不是必需的,除非您想在一行中有多个语句,否则不要使用它是一种约定。

【讨论】:

    【解决方案3】:

    由于您的函数返回一个字符串,您需要将s[start..&lt;end](即Substring)转换为String

    func substring(x : Int, y : Int, s : String) -> String {
      let start = s.index(s.startIndex, offsetBy: x);
      let end   = s.index(s.startIndex, offsetBy: y);
        return String(s[start..<end])
    }
    
    print(substring(x: 0, y: 2, s: "abcdefghijklmnopqrstuvwxyz"))
    

    输出:

    ab
    

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 2018-02-10
      • 2014-08-25
      相关资源
      最近更新 更多