【问题标题】:replacingOccurrences error替换发生错误
【发布时间】:2016-12-11 02:29:28
【问题描述】:

从 udacity 课程我正在尝试下面的代码

 let password = "Meet me in St. Louis"
 let newPassword = password.replacingOccurrences(of: "e", with: "3")

这是给的

Playground execution failed: Introduction.xcplaygroundpage:31:19: error: value of type 'String' has no member 'replacingOccurrences'
let newPassword = password.replacingOccurrences(of: "e", with: "3")
              ^~~~~~~~ ~~~~~~~~~~~~~~~~~~~~

强制我必须使用

let password = "Meet me in St. Louis"
let newPassword = password.stringByReplacingOccurrencesOfString("me", withString: "ss")

任何线索为什么会出现这个错误?我正在使用 swift 2.2 版

【问题讨论】:

  • 让 Swift 2.2 的 newPassword = password.stringByReplacingOccurrencesOfString("e",withString:"3")

标签: ios swift string swift2


【解决方案1】:

如果您从命令行运行此代码示例(通过运行 Swift REPL),请在 .swift 文件的开头添加 import Foundation

【讨论】:

  • 在空的 Playground 中也需要同样的导入
  • 我刚刚在 REPL 中执行了import Foundation,效果也很好。
【解决方案2】:

确保您拥有 Swift 3+ 版本

另外,请确保您:

 import Foundation

【讨论】:

    【解决方案3】:

    string.replacingOccurrences(of: "word", with: "newWord") 是一个 swift 3 API,因此游乐场给出错误是正确的:'String' 类型的值没有成员 'replacingOccurrences'

    在 Xcode 8 及更高版本中尝试相同的代码应该可以正常工作。

    【讨论】:

      【解决方案4】:

      我还参加了有关 Udacity 的课程。它是为 Swift 3 和 Xcode 8 设置的。确保您运行的是最新版本的 Xcode,然后再试一次。

      【讨论】:

        猜你喜欢
        • 2013-07-28
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        相关资源
        最近更新 更多