我想在扩展中添加一个类函数:
extension String {
class func test () {
}
}
我得到错误:类方法只允许在类中;使用’static’来声明静态方法
或者我该如何调用“String.test()”
但是对于Nsstring
extension Nsstring {
class func aaa () {
}
}
没有错误.
如果我添加静态关键字:
extension String {
static func aaa () {
self.stringByAppendingString("Hello")
}
}
得到:表达式解析为未使用的函数,
那么我应该如何添加一个类函数也想使用self.方法.
编辑:这有效!
extension String {
static func aaa (path:String) -> String {
return path.stringByAppendingString("Hello")
}
}
但关于@ lan的回答:
mutating func bbb(path: String) {
self += "world"
}
当我输入它时,它显示如下:
String.bbb(&<#String#>) String.bbb(&"nihao") Cannot invoke 'bbb' with an argument list of type '(String)'
类和结构的实例上不调用类和静态函数,而是在类/结构本身上调用,因此不能只是将字符串附加到类.
Apple Documentation:
Within the body of a type method,the implicit self property refers to
the type itself,rather than an instance of that type.
但是,您可以使用mutating关键字将字符串附加到String的变量实例:
extension String {
mutating func aaa() {
self += "hello"
}
}
let foo = "a"
foo.aaa() // Immutable value of type 'String' only has mutating members named 'aaa'
var bar = "b"
bar.aaa() // "bhello"
如果您尝试使用指向字符串的指针作为参数,则可以使用inout关键字来更改输入的字符串:
extension String {
static func aaa(inout path: String) {
path += "Hello"
}
}
var foo = "someText"
String.aaa(&foo)
foo //someTextHello