无法分配类型为'String'的值?键入“用户?”

时间:2019-07-25 23:35:12

标签: ios swift firebase

我尝试使用以下代码执行从按钮到特定用户ID chatController的选择:

@IBAction func toChatPressed(_ sender: Any) {
    let user = jobDetails?.userID
    let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
    chatLogController.user = user
    navigationController?.pushViewController(chatLogController, animated: true)
}

但是它给了我无法分配类型为'String'的值?键入“用户?” 作为错误...

chatController.user:

var user: User? {
    didSet {
        navigationItem.title = user?.name
        observeMessages()
    }
}

我从tableViewCell获得了用户ID,并保存在结构中

struct JobDetails {
    var jobDetail: String
    var userName: String
    var userImage: UIImage?
    var jobImage: UIImage?
    var downloadURL: String?
    var userLocation: String
    var userID: String?
}

3 个答案:

答案 0 :(得分:0)

chatController中,属性user的类型为User,即

var user: User? {
    ....
}

现在,从toChatPressed(_:)方法中,您可以将userID的值设置为chatController's user,这从代码中可以明显看出,

let user = jobDetails?.userID 

这里userIDString?。因此,以上代码中的user类型为String?

chatLogController.user = user 

在上面的代码中,您正在将user(类型为String?)分配给chatLogController.user(类型为User)。这就是您的错误的意思。

解决方案:

可以使用2个选项来解决此问题。

1。。要么在userID中创建类型为String?的属性chatLogController,即

var userID: String?

现在,从toChatPressed(_:)进行设置,

chatLogController.userID = jobDetails?.userID

2。。或者,您可以使用User中的jobDetails创建一个toChatPressed(_:)对象,然后将其设置为chatLogController's {{1} },即

user

如果您仍然有任何困惑,请随时提出。

答案 1 :(得分:-1)

您正在将main.cpp, C.h, and C-inl.h分配给JobDetails.userID: String?

查看您的代码:

ChatLogController.user: User?

您必须将 let user = jobDetails?.userID … chatLogController.user = user 映射到jobDetails?.userID: String

答案 2 :(得分:-1)

在您的struct JobDetails内,添加一个包含User对象的新字段:

struct JobDetails {
    var jobDetail: String
    var userName: String
    var userImage: UIImage?
    var jobImage: UIImage?
    var downloadURL: String?
    var userLocation: String
    var userID: String?
    var user: User? // <-- New field
}

无论何时创建新的JobDetails,都要将User对象传递到user字段。

现在,您可以使用user字段代替userID字段:

@IBAction func toChatPressed(_ sender: Any) {
    let user = jobDetails?.user // <-- user of type User? instead of userID of type String?
    let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
    chatLogController.user = user
    navigationController?.pushViewController(chatLogController, animated: true)
}