如何从SwiftUI中的函数返回枚举?

我想enum从我的函数中返回一个。为此,我需要对返回类型进行分类。

但是,如果我想返回一个,返回类型是enum什么?

我的代码如下:

class Timezone {
    
    func getTimeZoneFromCountry(country: String) -> ??? {
        switch country {
        case "AU":
            return Timezone.AU
        case "US":
            return Timezone.US
        default:
            return Timezone.AU
        }
    }
   
    enum AU: String, Identifiable, CaseIterable {
        case AEST = "AEST"
        case AWST = "AWST"
        case ACST = "ACST"
        
        var id: AU {self}
    }
    
    enum US: String, Identifiable, CaseIterable {
        case CST = "CST"
        case EST = "EST"
        case MST = "MST"
        case PST = "PST"
        
        var id: US {self}
    }

}

我正在尝试动态填充一个Picker

struct TimeZonePicker: View {
    @Binding var country: String // AU or US
    
    var body: some View {
        Picker("Timezone", selection: $country) {
            ForEach(*Dynamic enum here*) { i in
                Text(String(i.rawValue))
            }
        }
    }
}

编辑:@Sweeper 动态解决方案的新视图:

var body: some View {
    Picker("Timezone", selection: $country) {
        ForEach(Timezone.getTimeZoneFromCountry(country: country)) { i in
            Text(String(i.rawValue))
        }
    }
}

回答

使用单个枚举,并且只getTimeZoneFromCountry返回枚举的某些情况:

enum Timezone: String, Identifiable, CaseIterable {
    var id: Timezone { self }
    
    static func getTimeZoneFromCountry(country: String) -> [Timezone] {
        switch country {
        case "AU":
            return Timezone.AU
        case "US":
            return Timezone.US
        default:
            return Timezone.AU
        }
    }
    case AEST = "AEST"
    case AWST = "AWST"
    case ACST = "ACST"

    case CST = "CST"
    case EST = "EST"
    case MST = "MST"
    case PST = "PST"
    
    static let AU: [Timezone] = [.AEST, .AWST, .ACST]
    static let US: [Timezone] = [.CST, .EST, .MST, .PST]

}


以上是如何从SwiftUI中的函数返回枚举?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>