Be more formal about ProfileKey parsing

This commit is contained in:
Davide De Rosa 2019-03-08 10:21:08 +01:00
parent 05daa8f77a
commit ce3781e3b5
1 changed files with 11 additions and 6 deletions

View File

@ -26,6 +26,8 @@
import Foundation import Foundation
struct ProfileKey: RawRepresentable, Hashable, Codable { struct ProfileKey: RawRepresentable, Hashable, Codable {
private static let separator: Character = "."
let context: Context let context: Context
let id: String let id: String
@ -43,19 +45,22 @@ struct ProfileKey: RawRepresentable, Hashable, Codable {
// MARK: RawRepresentable // MARK: RawRepresentable
var rawValue: String { var rawValue: String {
return "\(context).\(id)" return "\(context)\(ProfileKey.separator)\(id)"
} }
init?(rawValue: String) { init?(rawValue: String) {
var comps = rawValue.components(separatedBy: ".") guard let separatorIndex = rawValue.firstIndex(of: ProfileKey.separator) else {
guard comps.count >= 2 else {
return nil return nil
} }
guard let context = Context(rawValue: comps[0]) else {
let contextValue = rawValue[rawValue.startIndex..<separatorIndex]
guard let context = Context(rawValue: String(contextValue)) else {
return nil return nil
} }
self.context = context self.context = context
comps.removeFirst()
id = comps.joined(separator: ".") let idStart = rawValue.index(after: separatorIndex)
let idEnd = rawValue.endIndex
id = String(rawValue[idStart..<idEnd])
} }
} }