How to make a Swift String enum available in Objective-C?

前端 未结 10 2180
情深已故
情深已故 2020-12-01 07:09

I have this enum with String values, which will be used to tell an API method that logs to a server what kind of serverity a message has. I\'m using Swift 1.2,

10条回答
  •  旧时难觅i
    2020-12-01 07:37

    Here's what I came up with. In my case, this enum was in the context providing info for a specific class, ServiceProvider.

    class ServiceProvider {
        @objc enum FieldName : Int {
            case CITY
            case LATITUDE
            case LONGITUDE
            case NAME
            case GRADE
            case POSTAL_CODE
            case STATE
            case REVIEW_COUNT
            case COORDINATES
    
            var string: String {
                return ServiceProvider.FieldNameToString(self)
            }
        }
    
        class func FieldNameToString(fieldName:FieldName) -> String {
            switch fieldName {
            case .CITY:         return "city"
            case .LATITUDE:     return "latitude"
            case .LONGITUDE:    return "longitude"
            case .NAME:         return "name"
            case .GRADE:        return "overallGrade"
            case .POSTAL_CODE:  return "postalCode"
            case .STATE:        return "state"
            case .REVIEW_COUNT: return "reviewCount"
            case .COORDINATES:  return "coordinates"
            }
        }
    }
    

    From Swift, you can use .string on an enum (similar to .rawValue). From Objective-C, you can use [ServiceProvider FieldNameToString:enumValue];

提交回复
热议问题