1

I have successfully subclassed the PFUser. PFUser has username and email properties.

What I would like to do is, accept an email for the username, and when the username is set, set the email property to username as well.

So I am trying to override the username property, so that I can update the email property accordingly. Below is what I have, which doesn't work :(. Any pointers please?

override public var username: String? {
    didSet {
        super.email = username
    }
}

(Note: PFUser is a class in Parse.com)

Thanks in advance.

oyalhi
  • 3,834
  • 4
  • 40
  • 45
  • A bit more detail is needed to understand your issue. What do you mean by "doesn't work"? Is the code in `username`'s `didSet` called? How are you checking the value of `email` before and after you set `username`? – Stuart Jul 21 '15 at 11:27
  • I put a breakpoint in the `super.email = username`. And in the code I set the username property like so: `var user: User` `user.username = "test"`. The `super.email = username` never gets called. This is all I am doing at the moment. Assuming that the overriden property will be called, but it does not. – oyalhi Jul 21 '15 at 11:29
  • 2
    Do you actually initialise your `user` instance? `var user: User` simply declares a variable `user` of type `User` but doesn't instantiate it, so subsequently trying to set the `username` property on it will fail (in fact, it should emit a compiler error "Variable 'user' used before being initialised". You initialise the `user` with a syntax more like this: `var user = User()`. – Stuart Jul 21 '15 at 11:40
  • I don't actually initiate the object, I just login the user and the User object gets created. However, it turns out that I was in fact testing the email change in a place where the user has not been created yet. After checking the code (after reading your post), I corrected it and `didSet` is in fact being called. Thank you!. By overriding the property, could I be breaking other code in the super class? Maybe the getters and setters are not working anymore because of the override? Is this possible or am I safe? – oyalhi Jul 21 '15 at 11:58
  • 1
    Overriding a property to add a property observer (`willSet`/`didSet`) is safe; each property observer is unique to the class in which it is declared. You could have further subclasses, each with their own property observers on overridden properties, and the superclass observers will continue to be called also. You can only 'break' the superclass implementation of a property if you override it and implement `set` or `get` without calling `super`, in which case the super implementation is never called. – Stuart Jul 21 '15 at 12:09
  • Thank you Stuart for the help. I appreciate it. – oyalhi Jul 21 '15 at 18:51

0 Answers0