Swift 如何为我的枚举返回空值

Swift 如何为我的枚举返回空值,swift,enums,Swift,Enums,我已经为我的支持类型设置了一个枚举,声明如下 enum SupportType: String, Codable { case type1 case type2 case type3 func string() -> String { switch self { case .type1: return "Type 1" case .type2:

我已经为我的支持类型设置了一个枚举,声明如下

enum SupportType: String, Codable {
    case type1
    case type2
    case type3

    func string() -> String {
        switch self {
            case .type1:
                return "Type 1"
            case .type2:
                return "Type 2"
            case .type3:
                return "Type 3"
    }
}
当我向类中添加时,我将类型声明为

type: SupportType
当传递值时,这一切都起作用,但当我尝试发送一个空白的新类型时,我尝试将其声明为

NewType(name: data.name, supportType: [SupportType(rawValue: "")], supportName: "")

这会抛出一个错误,表示它的值为空。如何在不使用现有类型值的情况下声明新类型?

为什么不使用
nil

首先将您的属性声明为可选:

var type: SupportType?
然后你可以通过零:

NewType(name: data.name, supportType: nil, supportName: "")

enum
的全部要点是,它只能用一个预定义的、不可变的实例进行实例化。
enum
类型只能接受在compile type中定义的值,在声明该类型后,您不能再向其添加任何案例,也不能修改其现有案例

string
函数也没有意义,您只需覆盖
enum
的默认
rawValue
,然后使用
string
rawValue
访问当前访问的属性

enum SupportType: String, Codable {
    case type1 = "Type 1"
    case type2 = "Type 2"
    case type3 = "Type 3"
}
如果为另一种类型定义了类型为
SupportType
的属性,则应将其定义为可选属性,而不是尝试为
SupportType
创建“空白值”。您还应该修改自定义初始值设定项,以便为
supportType
采用可选的输入参数

class NewType {
    let name:String
    var supportType:SupportType?
    var supportName:String?

    init(name: String, supportType: SupportType? = nil, supportName: String? = nil){
        self.name = name
        self.supportType = supportType
        self.supportName = supportName
    }
}
那就称它为

NewType(name: data.name, supportType: nil, supportName: nil)

它抛出一个错误“Nil与预期的类型SupportType不兼容”@leodbus,但OP将属性声明为
SupportType
,而不是
[SupportType]
@user616076您需要首先将声明更改为
SupportType?
。您这样做了吗?@user616076另外,如果您使用的是自定义初始值设定项,请将参数类型也更改为可选。