Swift enum associated values in Objective-C

前端 未结 2 943
梦谈多话
梦谈多话 2021-01-15 05:46
  1. Is there a way to use new Swift3 enums with associated value in Objective-C?
  2. Is there a way to declare/bridge Swift3 enums with associated value in Objective-
相关标签:
2条回答
  • 2021-01-15 05:54

    This is what I did:

    In Swift class created the enum

    enum Origin {
        case Search(searchTerm: String, searchResultsPageNum: Int)
        case Discovery(pageNum: Int)
    }
    

    Then in my Class, created enum property and functions (that are visible to Objective C) to set and get values of the enum property.

    @objc class GameSession: NSObject
    {
        ...
    
        var gameOrigin: Origin?
    
        ...
    
        let originStr = "origin"
        let notSpecified = "Not Specified"
    
        @objc func getOrigin() -> NSDictionary
        {
            guard let origin = gameOrigin else {
                return [originStr: notSpecified]
            }
    
            switch origin {
            case .Search(let searchTerm, let searchResultsPageNum):
                return ["searchTerm": searchTerm, "searchResultsPageNum": "\(searchResultsPageNum)"]
            case .Discovery(let pageNum)
                return ["pageNum": pageNum]
            default:
                return [originStr: notSpecified]
            }
        }
    
        @objc func setSearchOriginWith(searchTerm: String, searchResultsPageNum: Int, filtered:Bool)
        {
            self.gameOrigin = Origin.Search(searchTerm: searchTerm, searchResultsPageNum: searchResultsPageNum, filtered: filtered)
        }
    
        @objc func setDiscoveryOriginWith(pageNum: Int)
        {
            self.gameOrigin = Origin.Discovery(pageNum: pageNum)
        }
    
    }
    
    0 讨论(0)
  • 2021-01-15 06:10

    I'm afraid it's not possible, Apple has a list of Swift Type Compatibility which explicitly excludes enumerations defined in Swift without Int raw value type.

    Reference

    0 讨论(0)
提交回复
热议问题