4

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?

lishtenfour
  • 71
  • 1
  • 3
  • 4
    Please post actual code instead of screenshots. [See here](http://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang Dec 03 '15 at 03:12
  • `Self` is only intended to be used for generic constraints. What you likely want to do is using `self.dynamicType`. – fluidsonic Dec 03 '15 at 03:28
  • You would return something like `self.dynamicType.init()`. But you can only call initializers marked as `required`. – fluidsonic Dec 03 '15 at 04:05

2 Answers2

16

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
}
Ravindra_Bhati
  • 1,071
  • 13
  • 28
-2

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

Community
  • 1
  • 1
  • 3
    Hey there, see OP's question was what is the difference between the two, not which to use. So please include an actual answer to the question in your post. – LinusGeffarth Dec 03 '15 at 14:23
  • also, advise to google things should be a comment, not an answer :) – Hacketo Dec 03 '15 at 14:25
  • Well, sometimes, that is the only answer you can give when the answer is already readily available on the web... –  Dec 03 '15 at 14:26