Ahad Sheriff Ahad Sheriff - 3 months ago 14
Swift Question

Swift: How do I subclass an object so that I can add an extra variable?

I am building an app using a 3rd party framework and they have a default object (called

JSQMessage
) that has 3 parameters (
id
,
text
, and
displayName
):

func addMessage(id: String, text: String, displayName: String) {
let message = JSQMessage(senderId: id, displayName: displayName, text: text)
messages.append(message)
}


I want to add another parameter to the object called
score
as such:

func addMessage(id: String, text: String, displayName: String, score: Int) {

let message = JSQMessage(senderId: id, displayName: displayName, text: text, score: score)
messages.append(message)
}


However I keep getting the error
Argument labels '(senderId:, displayName:, text:, score:)' do not match any available overloads


I know that I must subclass the JSQMessage object and add my extra variable to your subclassed object...except I do not know how to do this.

I have created a new subclass of JSQMessage called
CustomMessage.swift
and it looks like such:

class CustomMessage: JSQMessage {

}


Now how do I go about adding an extra parameter to the object?

Note that the object looks like this:
JSQMessage(id: String, text: String, displayName: String)


But I want it to accept another parameter like this:
JSQMessage(id: String, text: String, displayName: String, score: Int)


I would appreciate it a lot if somebody could help me out here.

P.S. Let me know if you need any more information

Answer

You need to create a new class. The syntax would be something like

class MyMessage : JSQMessage {
}

You would add your extra attribute to the class

class MyMessage : JSQMessage {
    var score : Int
}

[I'm guessing that your score is an Int here.]

Then you would need to add an initializer

class MyMessage : JSQMessage {
    var score : Int

    init(senderID:Int, displayName:String, text:String, score:Int) {
        self.score = score
        super.init(senderID:senderID, displayName:displayName, text:text)
    }
}

If you're having trouble with this kind of thing then I strongly recommend that you spend some time with Apple's free book The Swift Programming Language, because this is basic Swift stuff.

Comments