面试题答案
一键面试在SwiftUI中,可以通过泛型来创建动态类型的视图。以下是一个示例,展示如何根据传入的数据类型动态调整显示方式:
import SwiftUI
struct GenericView<T> : View {
let value: T
var body: some View {
if let intValue = value as? Int {
Text("The integer value is \(intValue)")
} else if let stringValue = value as? String {
Text("The string value is \(stringValue)")
} else {
Text("Unsupported type")
}
}
}
struct ContentView: View {
var body: some View {
VStack {
GenericView(value: 42)
GenericView(value: "Hello, World!")
}
}
}
在上述代码中:
GenericView
是一个泛型视图,它接受一个类型为T
的值value
。- 在
body
中,使用as?
进行类型转换,判断value
是否为Int
或String
类型,并根据类型显示不同的文本格式。如果不是这两种类型,则显示 "Unsupported type"。 - 在
ContentView
中,展示了如何使用GenericView
并分别传入Int
和String
类型的值。