我应该如何使用Swift Enums实现默认关联值?

时间:2015-04-22 19:46:13

标签: swift enums

Swift问题是否有一种方法可以使用一个具有相关值的案例的枚举类型。

我有一个API,它为我提供了可用的过滤器,它不太可能,但API可能会添加其他过滤器类型。因此,如果API发送未知的过滤器类型,我希望保留与枚举相关联的信息。

以下是我对此做出的不同想法。

我的前两次尝试没有编译。我的第三次尝试感觉有点笨拙。

有没有人有更好的方法呢?你认为我不应该使用枚举来解决这个问题吗?

typealias APIFilterIdentifier = String

/* Does Not Compile */
enum EnumTestAssociatedValeu: APIFilterIdentifier {
    case Unknown(APIFilterIdentifier)
    case Everyone = "everyone"
    case Team = "myteam"
}

/* Does not compile */
enum EnumTestDefaultAssociatedValues: APIFilterIdentifier {
    case Unknown(APIFilterIdentifier)
    case Everyone(APIFilterIdentifier = "everyone")
    case Team(APIFilterIdentifier = "myteam")
}

/* Compiles but is there a better way? */
enum EnumTestWithCustomInit {

    case Unknown(APIFilterIdentifier)
    case Everyone
    case Team

    init(filterIdentifier: APIFilterIdentifier) {
        let everyone: APIFilterIdentifier = EnumTestWithCustomInit.everyoneFilterIdentifier
        let team: APIFilterIdentifier = EnumTestWithCustomInit.teamFilterIdentifier

        switch filterIdentifier {
        case everyone:
            self = .Everyone
        case team:
            self = .Team
        default:
            self = .Unknown(filterIdentifier)
        }
    }

    func asIdentifer() -> APIFilterIdentifier {
        switch self {
        case .Everyone:
            return EnumTestWithCustomInit.everyoneFilterIdentifier
        case .Team:
            return EnumTestWithCustomInit.teamFilterIdentifier
        case .Unknown(let filterIdentifier):
            return filterIdentifier
        }
    }

    private static var everyoneFilterIdentifier: APIFilterIdentifier {
        return "everyone"
    }

    private static var teamFilterIdentifier: APIFilterIdentifier {
        return "myteam"
    }
}

3 个答案:

答案 0 :(得分:8)

我知道这有点老了,但这会对你想要的东西起作用吗?

typealias FilterIdentifier = String

enum DefaultAPIFilters: FilterIdentifier {
    case Everyone = "everyone"
    case Team = "team"
}

enum APIFilters {
    case Default(DefaultAPIFilters)
    case Custom(FilterIdentifier)
}

let everyoneFilter = APIFilters.Default(.Everyone)
let teamFilter = APIFilters.Default(.Team)
let clownFilter = APIFilters.Custom("clowns_only")

答案 1 :(得分:4)

延长内森佩里的回应:

您可以添加

var underlyingString: String {
  return getUnderlyingString(self) 
}

到枚举。然后定义

func getUnderlyingString(apiFilter: APIFilters) -> String { 
    switch apiFilter {
    case .Default(let defaultAPIFilter):
        return defaultAPIFilter.rawValue
    case .Custom(let custom):
        return custom
    }
}

答案 2 :(得分:0)

根据此答案:Default value for Enum in Swift

我建议使用这种方法

public enum Result {
    case passed(hint: String)
    case failed(message: String)

    static let passed: Self = .passed(hint: "")
}


let res: Result = Result.passed