How to use Realm Swift Init
Here's my answer for iOS 13
, Swift 5
.
Being totally honest with you, I had no idea what I was doing, but I managed it to work by doing so:
class Account: Object {
@objc dynamic var name: String = ""
@objc dynamic var balance: Double = 0.0
@objc dynamic var savings: Double = 0.0
@objc dynamic var available: Double = 0.0
init(name: String, balance: Double){
self.name = name
self.balance = balance
self.savings = 0.0
self.available = balance
}
required init() {
//fatalError("init() has not been implemented")
}
}
Keep in mind that I'm totally new with Swift (about 3 months top), and I don't know the consequences of doing that. But my project is working just fine. Everything is being saved and retrieved perfectly.
Overriding Object.init()
and Object.init(_:)
are not yet supported in Realm Swift, but you can follow https://github.com/realm/realm-cocoa/issues/1849 for updates!
My solution in Swift 3
Custom initializer:
class Branches: Object {
dynamic var key: String = NSUUID().uuidString
dynamic var formattedAddress: String = ""
dynamic var latitude: Double = 0.0
dynamic var longitude: Double = 0.0
convenience init(formattedAddress: String, latitude: Double, longitude: Double) {
self.init()
self.formattedAddress = formattedAddress
self.latitude = latitude
self.longitude = longitude
}
override static func primaryKey() -> String? {
return "key"
}
}