gpt4 book ai didi

ios - 可选([值])!产生 nil (错误),尽管它有一个值

转载 作者:行者123 更新时间:2023-11-29 05:56:41 25 4
gpt4 key购买 nike

我有以下可选代码。

"\(postArray[indexPath.row].user.username)"

当我打印该值时,我得到类似以下内容的信息: 可选(“你好曼”)但是当我强制展开以摆脱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 获得的每个用户(我从用户关注列表中获得),我调用此方法

最佳答案

很可能在某些时候无法设置可选值。因此,您应该尝试使用 guardif let 来确保您在设置值时获取该值,并避免在其为零时使应用程序崩溃。

关于ios - 可选([值])!产生 nil (错误),尽管它有一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com