如果一個ObjC函數返回一個帶有枚舉的狀態值,是否有辦法在Swift 3中獲取該枚舉的字符串?如果我這樣做debugPrint("\(status)")
或print("\(status)")
我只是獲取枚舉的名稱而不是值。如果我做status.rawValue
,我得到int,但它並不意味着很多解釋。在Swift 3中獲取ObjC Enum的名字?
6
A
回答
2
如果print(x)
給你你想要的,然後使用String(describing:)
。這幾乎總是正確的答案。 (一般來說,這相當於"\(x)"
,它們不一定是相同的,但我還沒有發現一個案例,但他們沒有。)如果只有debugPrint()
給你你想要的,然後使用String(reflecting:)
。
對這些結果要非常小心。他們沒有本地化,也沒有承諾在發佈之間保持一致。它們不是一個序列化API。沒有任何承諾可以扭轉它們給你原始數據。這些用於枚舉的方法的輸出在Swift 3中發生了巨大的變化。我預計它們會隨着基金會進一步爲Swift進一步改進而再次發生變化。
我不想過分地恐慌你這些方法。 String(describing:)
在某些情況下(特別是實現特定協議的自定義類型)很好地定義了它返回的內容,但不是在所有情況下。您必須閱讀文檔並對其採取合理的謹慎措施。另一方面,String(reflecting:)
明確地「適合於調試」。我不會賭這個字符串的任何東西。
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"
}
}
}
相關問題
- 1. Swift 3 - 動態與@objc
- 2. 在Swift中獲取初始值3
- 3. 在Swift中獲取JSON元素3
- 4. 在swift中獲取錯誤3 xcode 8
- 5. 在Swift中獲取時差3
- 6. 在Swift 3中獲取當前日期?
- 7. 在swift中訪問擴展名中的靜態變量-ObjC
- 8. 在Objc中定義的枚舉>在Swift中聲明>在Objc中使用
- 9. StringWithFormat「%.2ld」objc swift
- 10. ObjC,Swift to WinObjC
- 11. Swift 3獲取音頻流
- 12. 如何在swift 3中從base64獲取一個字節數組?
- 13. Enum Flag獲取多個顯示名稱
- 14. Swift:在self.description中獲取self.description
- 15. 在Swift中觀察ObjC類的屬性
- 16. 在Swift中獲取函數名稱
- 17. Swift enum和NSCoding
- 18. 獲取特定的字符範圍從字符串SWIFT 3
- 19. 從Swift中獲取XMPP的名單
- 20. Swift 3 SwiftyJson獲取未知的數組鍵名稱
- 21. 在Objc項目中使用Swift類
- 22. 在異步任務<Enum>中返回Enum並獲取值
- 23. 如何在Swift 3的UIBarButtonItem按鈕中獲取自定義圖像名稱?
- 24. 在swift中導入swift鏈接的objc類
- 25. 獲取子節點的孩子(SWIFT 3)
- 26. 如何在Xcode beta 3中的Swift中從UIImagePickerControllerDelegate獲取UIImage?
- 27. Swift - 從MetaType獲取類名?
- 28. Swift 3 - 從字典數組中獲取值
- 29. Swift 3:如何從字符串中獲取數組
- 30. 獲取JQL中Enum的值的計數
感謝您的答覆。 debugPrint()和print()都不給我我想要的東西。它只是打印枚舉類型的名稱,而不是值。有沒有解決方案? – jl303
你想打印什麼枚舉?順便說一句,這是沒有可能的。該名稱可能不存在於運行時。 –