NSObject.self()
method, which is likely not expected SW-W1017When using self
inside a Swift class or struct, it normally refers to the instance of the class or struct.
However, in certain cases, if self
is used in conjunction with the NSObject
class, it can unintentionally refer to the NSObject.self()
method instead of the instance of the class.
This can lead to unexpected behavior and subtle bugs.
The NSObject.self()
method returns the meta-class object for the NSObject
class, which is not what is intended when using self
inside a class or struct.
This can lead to issues such as calling class methods instead of instance methods or accessing properties that are not present in the class.
To fix this issue, it is recommended to use the type(of: self)
expression instead of NSObject.self()
when referring to the class type.
This ensures that the correct class or struct instance is referenced and prevents any potential bugs related to the NSObject.self()
method.
class Foo {
static var count = 0
func bar() {
let type = NSObject.self
type.count += 1
}
}
class Foo {
static var count = 0
func bar() {
let type = type(of: self)
type.count += 1
}
}