从初始化程序返回而不初始化所有存储的属性(self.ref未初始化)

时间:2017-07-25 15:01:35

标签: ios firebase firebase-realtime-database swift2

当我输入类似app的twitter的代码时,我从初始化程序返回错误,而不使用代码var ref:FIRDatabaseReference初始化所有存储的属性!说自我引用没有初始化

import Foundation
import FirebaseDatabase

struct meme {



var ref: FIRDatabaseReference!
var key: String!
var username: String!
var name: String!
var tweetId: String!
var tweetText: String!
var tweetImageURL: String!
var tweeterImageURL: String


init(username: String, memeId: String, memeText: String, memeImageURL: String, memerImageURL: String, name: String, key: String = ""){

    self.username = username
    self.name = name
    self.memeId = memeId
    self.memeImageURL = memeImageURL
    self.memeText = memeText
    self.memerImageURL = memerImageURL



}




init(snapshot: FIRDataSnapshot){

    self.name = snapshot.value!["name"] as! String
    self.memerImageURL = snapshot.value!["memerImageURl"] as! String
    self.memeText = snapshot.value!["memeText"] as! String
    self.memeImageURL = snapshot.value!["memeImageURL"] as! String
    self.username = snapshot.value!["username"] as! String
    self.name = snapshot.value!["name"] as! String
    self.ref = snapshot.ref
    self.key = snapshot.key
}

func toAnyObject() -> [String: AnyObject]{

    return ["name":name, "username":username, "memeText":memeText,"memeId":memeId,"memerImageURl":memerImageURL,"memeImageURL":memeImageURL]
}

}`

2 个答案:

答案 0 :(得分:0)

目标尚不清楚,但如果需要var,则应使用init中的默认值进行初始化

init() {
   self.key = "some key"
   self.userName = "some user name"
}

或者,改变struct / class vars

struct meme {
   var key = ""
   var userName = ""
}

并且vars可以即时启动

var aaa = meme()
aaa.key = "some key"
aaa.userName = "some username"

答案 1 :(得分:0)

第一个init方法显然没有设置" ref"这完全解释了你的问题。而且我不确定你为什么宣称一切都是强制选项。你有理由吗?无论如何,你的init方法都将所有内容(你错过的ref除外)初始化为非可选值。