在Swift中将常量字符串转换为变量字符串

在Swift中将常量字符串转换为变量字符串,swift,Swift,考虑一下这个假设的Swift函数: func putFirst(_ string: String) { var str = string let c = str.popFirst() print(c) } 基于前面的问题,例如,str是一个变量,因此是可变的。但是,str.popFirst()抛出编译错误 Cannot use mutating member on immutable value: 'str' is immutable 这是我不知道的微妙之处吗?这是S

考虑一下这个假设的Swift函数:

func putFirst(_ string: String) {
    var str = string
    let c = str.popFirst()
    print(c)
}
基于前面的问题,例如,
str
是一个变量,因此是可变的。但是,
str.popFirst()
抛出编译错误

Cannot use mutating member on immutable value: 'str' is immutable
这是我不知道的微妙之处吗?这是Swift 4的新行为吗?我该如何处理它呢?

它是;问题是在
集合
上只定义了一个
popFirst()
方法:

然后你会说:

func putFirst(_ string: String) {
  var str = string
  let c = str.attemptRemoveFirst()
  print(c)
}

先让c=str;str.dropFirst()
extension RangeReplaceableCollection {

  /// Removes and returns the first element of the collection.
  ///
  /// Calling this method may invalidate all saved indices of this
  /// collection. Do not rely on a previously stored index value after
  /// altering a collection with any operation that can change its length.
  ///
  /// - Returns: The first element of the collection if the collection is
  ///   not empty; otherwise, `nil`.
  ///
  /// - Complexity: O(n)
  public mutating func attemptRemoveFirst() -> Element? {
    return isEmpty ? nil : removeFirst()
  }
}
func putFirst(_ string: String) {
  var str = string
  let c = str.attemptRemoveFirst()
  print(c)
}