Swiftui-带有可选观察的Textfield

发布于 2025-01-30 17:33:46 字数 894 浏览 4 评论 0原文

在这里,我的视图带有一个文本字段,该文字字段读取了一个观察到的对象。观察到的对象具有可选类型的“用户”的属性“ Newuser?”。当我尝试解开“ newuser”以检索其用户名的文字文件时,我会发现一个错误,说我仍然必须解开它。

错误

纽瑟尔模型

struct NewUser: {
    var id: UUID?
    var username: String
}

观察对象

class HTTPUserClient: ObservableObject {
    
    @Published var user: NewUser? //a user struct with a non optional 
    //function and stuff ommitted
}

查看

import SwiftUI

struct TestUserEditor: View {
    @ObservedObject var userClient:HTTPUserClient
    
    var body: some View {
        TextField("required", text: $userClient.user!.username)   
    } 
}    

对象,

如果我使用上述代码,我会收到以下错误

Value of optional type 'NewUser?' must be unwrapped to refer to member 'firstName' of wrapped base type 'NewUser'

,但是如果我通过添加“!”来修复它,则强制解开用户,我会得到相同的错误

Here I have view with a textfield that reads off an ObservedObject. The Observed object has a property called "user" that is of optional type "NewUser?". When I try to unwrap the "NewUser" to retrieve its username for the textfied I get an error saying that I must still unwrap it.

The Errors

NewUser Model

struct NewUser: {
    var id: UUID?
    var username: String
}

Observed Object

class HTTPUserClient: ObservableObject {
    
    @Published var user: NewUser? //a user struct with a non optional 
    //function and stuff ommitted
}

View

import SwiftUI

struct TestUserEditor: View {
    @ObservedObject var userClient:HTTPUserClient
    
    var body: some View {
        TextField("required", text: $userClient.user!.username)   
    } 
}    

The errors

IF I use the above code I get the following error

Value of optional type 'NewUser?' must be unwrapped to refer to member 'firstName' of wrapped base type 'NewUser'

but if I fix it by adding a "!", force unwrapping the user, I get the same error

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2025-02-06 17:33:46

我的建议是通过添加静态示例作为占位符来摆脱可选。

struct NewUser {
    var id: UUID?
    var username: String

    static let example = NewUser(id: nil, username: "")
}

并声明用户

@Published var user = NewUser.example

My suggestion is to get rid of the optional by adding a static example as a placeholder.

struct NewUser {
    var id: UUID?
    var username: String

    static let example = NewUser(id: nil, username: "")
}

and declare user

@Published var user = NewUser.example
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文