【发布时间】:2017-06-17 11:04:27
【问题描述】:
我的意图如下:
我的第一个功能:
public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String
例如,我可以在print() 的上下文中使用它。
我的第二个:
public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void
只是为了修改一些东西。
我知道需要不同的函数签名,但有没有更好的方法?
【问题讨论】:
-
否,但您可以使用返回
String的函数,就好像它是Void。 -
听起来很完美。我怎样才能意识到这一点?
-
只调用它,不要将结果分配给任何变量。 Swift 会让你这么做。
-
但随后出现警告:“调用...的结果未使用”。
-
您还需要将其标记为
@discardableResult以指示不必使用返回值(比较Result of call to [myFunction] is unused)。但我不建议使用同时返回变异实例的mutating方法——如果在单独的行上调用该方法,然后再使用变异实例,则该方法的用法会更清晰。否则,乍一看,该方法可能会创建一个新字符串,而不是变异。
标签: swift function methods declaration