Skip to content

Instantly share code, notes, and snippets.

@kumamotone
Created September 15, 2018 17:33
Show Gist options
  • Save kumamotone/4c7ca76ae461ee32d5bb62d8ea054c42 to your computer and use it in GitHub Desktop.
Save kumamotone/4c7ca76ae461ee32d5bb62d8ea054c42 to your computer and use it in GitHub Desktop.
Use enum case's name
import Foundation
extension Encodable {
func asDictionary(convertToSnakeCase: Bool = false) throws -> [String: Any] {
let encoder = JSONEncoder()
if convertToSnakeCase { encoder.keyEncodingStrategy = .convertToSnakeCase }
let data = try encoder.encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
}
enum Region: Int, Codable, CaseIterable {
case 北海道
case 本州
case 中国四国
case 九州
var toString: String {
return String(describing: self)
}
}
struct SampleRequest: Encodable {
let regionType: Region
}
let indexPathRowSample = Region.allCases.count - 1
print(Region.allCases[indexPathRowSample].toString)
let region: Region = .九州
let request = SampleRequest(regionType: region)
let parameters = try request.asDictionary(convertToSnakeCase: true)
print(parameters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment