Created
September 15, 2018 17:33
-
-
Save kumamotone/4c7ca76ae461ee32d5bb62d8ea054c42 to your computer and use it in GitHub Desktop.
Use enum case's name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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