-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChild.swift
More file actions
77 lines (61 loc) · 2.35 KB
/
Child.swift
File metadata and controls
77 lines (61 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// Child.swift
// CP
//
// Created by Gavin Olsen on 5/8/17.
// Copyright © 2017 Gavin Olsen. All rights reserved.
//
import Foundation
import CloudKit
class Child: CloudKitSync {
//MARK: keys
static let typeKey = "Child"
static let nameKey = "nameKey"
static let parentKey = "parentKey"
static let detailsKey = "detailsKey"
static let ageKey = "ageKey"
static let carpoolKey = "carpoolKey"
static let ckRecordKey = "ckRecordIDkey"
//MARK: properties
var name: String
var age: Int
var ckReference: CKReference?
var parent: Parent?
var carpools: [Carpool] = []
var details: String?
var ckRecordID: CKRecordID?
var recordType: String { return Child.typeKey }
//MARK: initilizers
init(name: String, age: Int, details: String? = nil, parent: Parent? = nil, carpools: [Carpool] = [], ckReference: CKReference? = nil) {
self.name = name
self.age = age
self.details = details
self.parent = parent
self.carpools = carpools
}
convenience required init?(record: CKRecord) {
guard let name = record[Child.nameKey] as? String, let age = record[Child.ageKey] as? Int, let details = record[Child.detailsKey] as? String, let parent = record[Child.parentKey] as? CKReference else { return nil }
self.init(name: name, age: age, details: details, ckReference: parent)
ckRecordID = record.recordID
}
}
//MARK: extensions
extension Child: SearchableRecord {
func matches(searchTerm: String) -> Bool {
return name.contains(searchTerm)
}
}
extension CKRecord {
convenience init?(_ kid: Child) {
guard let parent = kid.parent else { NSLog("child doesn't have parent relationship"); return nil }
let parentRecordID = parent.ckRecordID ?? CKRecord(parent).recordID
let recordID = CKRecordID(recordName: UUID().uuidString)
kid.ckRecordID = recordID
self.init(recordType: kid.recordType, recordID: recordID)
self[Child.parentKey] = CKReference(recordID: parentRecordID, action: .deleteSelf)
self[Child.ageKey] = kid.age as CKRecordValue?
self[Child.nameKey] = kid.name as CKRecordValue?
self[Child.detailsKey] = kid.details as CKRecordValue?
self[Child.ckRecordKey] = recordID as? CKRecordValue
}
}