enter image description here

Question: What difference between 'self' and 'Self'? How do I use "Self" in a function implementaion When I define a function in a superclass to return subclass's type?

What type should I return on behalf of function caller's self type? Is base type NSObject or not?

2

Best Answer


When you’re writing protocols and protocol extensions, there’s a difference between Self (capital S) and self (lowercase S). When used with a capital S, Self refers to the type that conform to the protocol, e.g. String or Int. When used with a lowercase S, self refers to the value inside that type, e.g. “hello Swift” or 786.

As an example, consider this extension on BinaryInteger:

extension BinaryInteger {func squared() -> Self {return self * self}}

Remember, Self with a capital S refers to whatever type is conforming to the protocol. In the example above, Int conforms to BinaryInteger, so when called on Int the method effectively reads this:

func squared() -> Int {return self * self}

On the other hand, self with a lowercase S refers to whatever value the type holds. If the example above were called on an Int storing the value 8 it would effectively be this:

func squared() -> Int {return 8 * 8}

You should use self, not Self.

Also, as others have noted, try self.dynamicType.

Moreover, I would advise you to google "How to Check Type Swift" on Google.

Hope that helped :)

Quote from this link : Distinction in Swift between uppercase "Self" and lowercase "self"

"Self refers to the type of the current "thing" inside of a protocol (whatever is conforming to the protocol). For an example of its use, see Protocol func returning Self.

The only official docs I've found for Self is in Protocol Associated Type Declaration in The Swift Programming Language. It surprisingly is not documented in the sections on protocols or on nested types."

Moreover: https://forums.developer.apple.com/thread/5479