我想创建一个函数来改变变量的原始值。例如
class Something {
var name:String = " John Diggle "
name.trim()
print(name)
// prints out " John Diggle "
// what I wanna do is to make it so that I don't do this
name = name.trim()
print(name)
// prints out "John Diggle"
}
extension String {
func trim() -> String{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
有没有办法在不执行name = name.trim()
的情况下更改函数内部变量的值?
答案 0 :(得分:5)
也许是这样的?
extension String {
mutating func trim() {
self = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
然后您可以将其用作name.trim()
答案 1 :(得分:4)
为了扩展Tj3n的答案(你应该接受),API中新兴的约定是使用动词的过去时(例如trimmed
)来返回一个新的字符串,一个你可以使用的方法在常量和变量上,并使用现在时(例如trim
)进行变异再现,这只能用于变量:
extension String {
func trimmed() -> String {
return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
}
mutating func trim() {
self = self.trimmed()
}
}
因此,要么:
var name = " John Diggle "
name.trim()
print("'\(name)'")
或者:
let name = " John Diggle "
let trimmedName = name.trimmed()
print("'\(trimmedName)'")
答案 2 :(得分:1)
每次更改字符串时,您都可以使用didSet
修剪字符串:
class Something {
var name: String = "" {
didSet {
name = name.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
}
let s = Something()
s.name = " John Diggle "
// Note that we never call trim in the outside code
print("'\(s.name)'")