簡體   English   中英

比較Swift中的枚舉

[英]Compare enums in Swift

我有一個包含兩個這樣的枚舉的類(使之簡單):

class Errors {
    enum UserError: String {
        case NoToken = "No token!"
        case NoPassword = "No password!"
    }

    enum BackendError: String {
        case NoConnection = "No connection!"
        case ServerBusy = "Server is busy!"
    }
}

現在,我想編寫一個泛型函數,該函數可以接受UserError或BackendError並根據輸入返回字符串。 像這樣:

func alert(type: /* Accepts Error.UserError or BackendError*/) -> String {
    // checks if UserError or BackendError and returns .rawValue
}

我的第一種方法是使用泛型-但坦率地說,我在理解這個概念時遇到了麻煩,而且我傾向於在這里從根本上錯了。 我所做的是:

func alert<T>(type: T) {
    if type == Errors.UserError {
        return Errors.UserError.NoPassword.rawValue
    } else {
        return Errors.BackendError.NoConnection.rawValue
    }
 }

顯然,這是行不通的。

binary operator cannot be applied to operands of type 'T' and 'Errors.UserError.Type'

我知道這與缺少的實現等價/可比較協議以及我對使用泛型的普遍了解有關。 我的問題是:

  1. 如何將我的通用“類型”參數與枚舉進行比較?

  2. 我對仿制葯的理解完全錯誤嗎?

另外:我想避免使用AnyObject方法。

您的enums有一個共同點,並且您想利用的是它們是RawRepresentable ,而它們的RawValue類型是String

因此,您需要一個類似以下的函數:

func alert<T: RawRepresentable where T.RawValue == String>(t: T) -> String {
    return t.rawValue
}

希望我不要誤會你的意圖。 我假設您想讓泛型函數既可以接受枚舉,也可以打印出每個字符串。 也許您可以參考我的回答。

功能:

func alert<T: CustomStringConvertible>(t: T) -> String {
    return t.description
}

枚舉:



    enum UserError: String, CustomStringConvertible {
        case NoToken = "No token!"
        case NoPassword = "No password!"

        var description: String {
            return self.rawValue
        }
    }

    enum BackendError: String, CustomStringConvertible {
        case NoConnection = "No connection!"
        case ServerBusy = "Server is busy!"

        var description: String {
            return self.rawValue
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM