[英]How to define in swift an optional variable for a function type, which can be nil?
[英]How we can define a State variable type Any?
更新:此方法僅用於學習 Goal,未在實際項目中使用!(直到新更新)
在這里,我確實遇到了將 State var 定義為Any
類型的 2 個問題。 如您所知,我們必須對其進行初始化。 例如,在這段代碼中,我必須用 Image 初始化我的 State var,這不是我想要的,選擇 any 作為類型的所有要點是提供類型的自由,但是 State 將這種自由從我身上初始化,然后繼續最重要的是,我必須強制展開 State 才能使用它!
那么關於 var 類型 any with State 的 2 個問題(初始化+強制展開),我們有辦法解決這些問題嗎?
@State var anyItem: Any = UIImage(named: "apple")!
這是我在碩士的幫助下的新代碼更新:
import SwiftUI
struct ContentView: View
{
@State var anyItem: Any?
@State var changedType: Bool = false
init() {
_anyItem = .init(initialValue: UIImage(named: "Apple"))
}
var body: some View {
if changedType == false
{
Image(uiImage: anyItem as! UIImage)
}
else
{
Text(anyItem as! String)
}
Text("Test")
.onTapGesture
{
chandType.toggle()
anyItem = "anyItem changed to Text! Kaboom!"
}
}
}
V2:高級版
import SwiftUI
struct ContentView: View
{
@State var anyItem: Any?
enum anyItemType { case String, Image, Unknowen }
@State var choosenType: anyItemType = anyItemType.Unknowen
var body: some View {
ZStack
{
VStack
{
if choosenType == anyItemType.String
{
Text(anyItem as! String).bold()
}
else if choosenType == anyItemType.Image
{
Image(uiImage: anyItem as! UIImage).resizable().frame(width: 200, height: 200, alignment: .center).clipShape(Circle())
}
}
VStack
{
Spacer()
Button(choosenType == anyItemType.String ? "Change anyItem Type to Image" : "Change anyItem Type to String")
{
if choosenType == anyItemType.String
{
anyItem = UIImage(named: "Apple")
choosenType = anyItemType.Image
}
else
{
anyItem = "anyItem changed to Text! KABOOOM!"
choosenType = anyItemType.String
}
}.font(Font.body.bold())
}
.padding(.bottom, 100)
}
}
}
問題不是因為Any
。 這是因為這一行:
UIImage(named: "apple")
返回一個可選的( UIImage?
)。
如果您希望anyItem
接受UIImage?
類型的值UIImage?
你需要做Any?
:
@State var anyItem: Any? = UIImage(named: "apple")
或提供可選的默認值:
@State var anyItem: Any = UIImage(named: "apple") ?? UIImage()
這是一個示例,說明如何使用不同類型初始化anyItem
(這僅用於演示,可能不應在實際應用程序中使用):
struct ContentView: View {
@State var anyItem: Any?
init() {
_anyItem = .init(initialValue: UIImage(named: "apple"))
}
var body: some View {
Text("Test")
.onAppear {
anyItem = "test"
}
}
}
但是正如 Asperi 已經建議的那樣,這不是一個好主意,您通常希望避免在 SwiftUI 中使用Any
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.