Swift enum associated values in Objective-C

前端 未结 2 944
梦谈多话
梦谈多话 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)
        }
    
    }
    

提交回复
热议问题