我有下面的代码是可选的。
"\(postArray[indexPath.row].user.username)"
当我打印值时,我得到类似以下内容: 可选(“ helloman”) 但是当我强制拆开以摆脱Optional()时,应用程序崩溃了 零。 为什么会这样?我该如何解决?
我打印:
print(postArray[indexPath.row].user.username, " loop full\(indexPath.row)")
print(postArray[indexPath.row].user.username!, " loop full\(indexPath.row)")
并获得以下结果
nil loop full2
//在此处崩溃
我将用户添加到每个帖子对象中,如下所示:
func retrieveUsersInfo(userObj: User) {
let ref = Database.database().reference()
if userObj.userID != nil {
print("inside if of retrieveUsers")
let UID = userObj.userID!
print(UID, "<-- uid promg")
let currentUID = "\(UID)"
print(currentUID, "<<- current uid")
print(lastUID, "<-- chhhc")
if lastUID == nil {
print("last uid 6was nil")
ref.child("users2").child(UID).observe(.value, with: { (snapshot) in
print(snapshot.childSnapshot(forPath: "username").value as! String, "0302310320101320312032101")
print("here?")
do {
self.addUserDataToObject(userObj: userObj, snapshot: snapshot)
}
})
} else if currentUID == lastUID! {
print("hello?")
ref.child("users2").child(UID).observe(.value, with: { (snapshot) in
print(snapshot.childSnapshot(forPath: "username").value as! String, "0302310320101320312032101")
do {
self.addUserDataToObject(userObj: userObj, snapshot: snapshot)
}
})
} else if currentUID != lastUID! {
print("vai malandra") //the stuff below should be made into another function to reduce text; be more fficient
ref.child("users2").child(UID).observe(.value, with: { (snapshot) in
print(snapshot.childSnapshot(forPath: "username").value as! String, "0302310320101320312032101")
do {
self.addUserDataToObject(userObj: userObj, snapshot: snapshot)
}
})
} else {
print("gggg")
}
lastUID = "\(UID)"
}
}
使用白粉功能:
func addUserDataToObject(userObj: User, snapshot: DataSnapshot) {
if "\(snapshot.childSnapshot(forPath: "username").value as! String)" != nil {
userObj.fullName = "\(snapshot.childSnapshot(forPath: "fullName").value as! String)"
userObj.username = "\(snapshot.childSnapshot(forPath: "username").value as! String)"
userObj.profileImageUrl = "\(snapshot.childSnapshot(forPath: "profileImage").value as! String)"
} else {
print("the username was nil!")
}
}
对于我从.childAdded中获得的每个用户(从下面的用户列表中获得),我都调用此方法