jdog
jdog

Reputation: 10769

How to resolve initializers in Swift

Newbie to Swift coming from Obj-c.

I am following this Udemy tutorial on building an Uber clone with Swift. It appears the code in the tutorial must be old?

Below is the code he uses (he doesn't get a single error).

import Foundation
import Firebase

let DB_BASE = Database.database().reference()

class DataService {  << class DataService has no initializers
    static let instance = DataService()  << No accessible initializers

    private var _REF_BASE = DB_BASE
    private var _REF_USERS = DB_BASE.child("users")
    private var _REF_DRIVERS = DB_BASE.child("drivers")
    private var _REF_TRIPS = DB_BASE.child("trips")

    var REF_BASE = DatabaseReference() {  << Arg passed to call that takes no Arg
        return _REF_BASE
    }

    var REF_USERS: DatabaseReference() {  << Unexpected initializers pattern; did you mean =
        return _REF_USERS
    }

    var REF_DRIVERS: DatabaseReference() {  << Unexpected initializers pattern; did you mean =
        return _REF_DRIVERS
    }

    var REF_TRIPS: DatabaseReference() {  << Unexpected initializers pattern; did you mean =
        return _REF_TRIPS
    }


}

See the below photo for all the initializer errors. Cannot seem to get them resolved.

enter image description here

Upvotes: 0

Views: 79

Answers (1)

vadian
vadian

Reputation: 285270

Don't try to translate ObjC code to Swift literally. For example Swift doesn't know backing instance variables and it's bad practice to name properties capitalized and snake_cased.

A reasonable Swift singleton with let constants is

import Foundation
import Firebase

public class DataService {

    public let database : DatabaseReference
    public let usersRef : DatabaseReference
    public let driversRef : DatabaseReference
    public let tripsRef : DatabaseReference

    public static let instance = DataService()

    private init() {
       database = Database.database().reference()
       usersRef = database.child("users")
       driversRef = database.child("drivers")
       tripsRef = database.child("trips")
    }   
}

Upvotes: 2

Related Questions