2016-11-27 43 views
6

如果一個ObjC函數返回一個帶有枚舉的狀態值,是否有辦法在Swift 3中獲取該枚舉的字符串?如果我這樣做debugPrint("\(status)")print("\(status)")我只是獲取枚舉的名稱而不是值。如果我做status.rawValue,我得到int,但它並不意味着很多解釋。在Swift 3中獲取ObjC Enum的名字?

回答

2

如果print(x)給你你想要的,然後使用String(describing:)。這幾乎總是正確的答案。 (一般來說,這相當於"\(x)",它們不一定是相同的,但我還沒有發現一個案例,但他們沒有。)如果只有debugPrint()給你你想要的,然後使用String(reflecting:)

對這些結果要非常小心。他們沒有本地化,也沒有承諾在發佈之間保持一致。它們不是一個序列化API。沒有任何承諾可以扭轉它們給你原始數據。這些用於枚舉的方法的輸出在Swift 3中發生了巨大的變化。我預計它們會隨着基金會進一步爲Swift進一步改進而再次發生變化。

我不想過分地恐慌你這些方法。 String(describing:)在某些情況下(特別是實現特定協議的自定義類型)很好地定義了它返回的內容,但不是在所有情況下。您必須閱讀文檔並對其採取合理的謹慎措施。另一方面,String(reflecting:)明確地「適合於調試」。我不會賭這個字符串的任何東西。

+0

感謝您的答覆。 debugPrint()和print()都不給我我想要的東西。它只是打印枚舉類型的名稱,而不是值。有沒有解決方案? – jl303

+0

你想打印什麼枚舉?順便說一句,這是沒有可能的。該名稱可能不存在於運行時。 –

3

Objective-C enum個案的名稱在運行時不存在 - 它們只是整數值,與Swift的enum不同,它們具有與它們關聯的運行時信息。如果你想在運行時使用各個案例的名字,你必須單獨存儲它們,並通過整數值來訪問它們(即從int值轉換爲人類可識別的名稱)。

2

您還可以將Obj-C enum的一致性添加到CustomStringConvertible並以這種方式將值轉換爲字符串。只要你不使用default,你將會被警告,如果這些值在未來的版本中有任何變化。

例如:

extension NSLayoutAttribute : CustomStringConvertible { 
    public var description: String { 
     switch self { 
     case .left : return "left" 
     case .right : return "right" 
     case .top : return "top" 
     case .bottom : return "bottom" 
     case .leading : return "leading" 
     case .trailing : return "trailing" 
     case .width : return "width" 
     case .height : return "height" 
     case .centerX : return "centerX" 
     case .centerY : return "centerY" 
     case .lastBaseline : return "lastBaseline" 
     case .firstBaseline : return "firstBaseline" 
     case .leftMargin : return "leftMargin" 
     case .rightMargin : return "rightMargin" 
     case .topMargin : return "topMargin" 
     case .bottomMargin : return "bottomMargin" 
     case .leadingMargin : return "leadingMargin" 
     case .trailingMargin : return "trailingMargin" 
     case .centerXWithinMargins : return "centerXWithinMargins" 
     case .centerYWithinMargins : return "centerYWithinMargins" 
     case .notAnAttribute : return "notAnAttribute" 
     } 
    } 
}