SubClass Parse.com object with Apple Swift
We’ve been working on upgrading our projects to use the new Swift language. In this blog I will show you how to subclass an PFObject in swift language.
Note: This article assume you have the base understanding of the usage of Parse.com, and Swift programming language.
Alternatively, here’s the subclass tut for Java.
in the official documentation, Parse give out an example on how to subclass Armor in Objective-C. The following is a Swift version of Armor subclass.
//======================================================== // Armor is a subclass of PFObject // Class name: Armor // Author: Xujie Song // Copyright (c) 2015 SK8 PTY LTD. All rights reserved. //======================================================== import Foundation class Armor : PFObject, PFSubclassing { // ======================================================= // Constructors // ======================================================= //Required,regardless which class you’re subclassing from. class func parseClassName() -> String? { return "Armor" } //Required, can be private or public(Just remove private keyword) private override init() { super.init(); } //Custom constructor(Called initializer in Swift) init(displayName: String) { super.init(); self.displayName = displayName; } // ======================================================= // Instance Property // ======================================================= //For instance, Armor had a instance property called “displayName”. //In OC, use @Dynamic. In swift, the equivalent is @NSManaged. //Please ensure “keyName” is the same as @NSManaged var keyName. //Do not miss @NSManaged //Also ensure do not include instance property with the same name. @NSManaged var displayName: String? //======================================================== // Property setters and getters // ======================================================= //Property setter and getter is not required in Swift. //Or at lease it should be done like this. //To keep the code in sync with our Android version, I did in Java fashion func getDisplayName() -> String? { //return self["displayName"]; or return self.objectForKey("displayName") as? String; } func setDisplayName(displayName: String) { //self["displayName"] = name; 或 self.setObject(name, forKey: "displayName"); } // ====================================================== // Class Method //====================================================== class func classMethod() -> Bool { return false; } // ====================================================== // Instance Method // ====================================================== func hadName() -> Bool { if let name = self.displayName { return name.length > 0 } else { return false; } } }












