gpt4 book ai didi

swift - 多态性和 SwiftUI

转载 作者:行者123 更新时间:2023-12-03 19:19:51 26 4
gpt4 key购买 nike

给出以下示例:

class ProfileTab: Identifiable {
let id = UUID()
let name: String

init(name: String) {
self.name = name
}
}

class ProfileQuoteTab: ProfileTab {
let answer: String
let prompt: String

init(name: String, answer: String, prompt: String) {
self.answer = answer
self.prompt = prompt
super.init(name: name)
}
}

class ProfileImageTab: ProfileTab {
let image: Image

init(name: String, image: Image) {
self.image = image
super.init(name: name)
}
}

struct ContentView: View {
let tabs: [ProfileTab] = [
ProfileQuoteTab(name: "This is a quote tab", answer: "This is an answer", prompt: "This is a prompt"),
ProfileImageTab(name: "This is an image tab", image: Image(systemName: "faceid"))
]

var body: some View {
List(self.tabs) { tab in
VStack {
if tab is ProfileQuoteTab {
Text((tab as! ProfileQuoteTab).answer)
}

if tab is ProfileImageTab {
(tab as! ProfileImageTab).image
}
}
}
}
}

是否有更好/推荐的方法来访问我的 ProfileTab 中不同类的属性?大批?

我知道这样做会导致:

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'


if let profileImage = tab as? ProfileImage {
...
}

有没有更清洁的方法而不是执行以下操作?
(tab as! ProfileImageTab).image

最佳答案

在所描述的用例中,多态性将如下所示(或在某些变体中):

class ProfileTab: Identifiable {
let id = UUID()
let name: String

init(name: String) {
self.name = name
}

func view() -> AnyView {
AnyView(EmptyView())
}
}

class ProfileQuoteTab: ProfileTab {
let answer: String
let prompt: String

init(name: String, answer: String, prompt: String) {
self.answer = answer
self.prompt = prompt
super.init(name: name)
}

override func view() -> AnyView {
AnyView(Text(self.answer))
}
}

class ProfileImageTab: ProfileTab {
let image: Image

init(name: String, image: Image) {
self.image = image
super.init(name: name)
}

override func view() -> AnyView {
AnyView(self.image)
}
}

struct ContentView: View {
let tabs: [ProfileTab] = [
ProfileQuoteTab(name: "This is a quote tab", answer: "This is an answer", prompt: "This is a prompt"),
ProfileImageTab(name: "This is an image tab", image: Image(systemName: "faceid"))
]

var body: some View {
List(self.tabs) { tab in
VStack {
tab.view()
}
}
}
}

关于swift - 多态性和 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607316/

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