Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions Samples/Swift/DaysUntilBirthday/Shared/Models/Birthday.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import Foundation

/// A model type representing the current user's birthday.
struct Birthday: Decodable {
let integerDate: Birthday.IntegerDate
fileprivate let integerDate: Birthday.IntegerDate

/// The birthday as a `Date`.
var date: Date? {
Expand All @@ -30,7 +30,7 @@ struct Birthday: Decodable {
year: currentYear.year,
month: integerDate.month,
day: integerDate.day)
guard let d = comps.date else { return nil }
guard let d = comps.date, comps.isValidDate else { return nil }
if d < now {
var nextYearComponent = DateComponents()
nextYearComponent.year = 1
Expand All @@ -39,12 +39,20 @@ struct Birthday: Decodable {
} else {
return d
}
}
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.integerDate = try container.decode(IntegerDate.self, forKey: .integerDate)
}

init(integerDate: IntegerDate) {
self.integerDate = integerDate
}

static var noBirthday: Birthday? {
return Birthday(integerDate: IntegerDate(month: .min, day: .min))
}
}

extension Birthday {
Expand All @@ -64,7 +72,7 @@ extension Birthday {
extension Birthday: CustomStringConvertible {
/// Converts the instances `date` to a `String`.
var description: String {
return date?.description ?? "NA"
return date?.description ?? "No birthday"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,15 @@ final class BirthdayViewModel: ObservableObject {
@Published private(set) var birthday: Birthday?
/// Computed property calculating the number of days until the current user's birthday.
var daysUntilBirthday: String {
guard let bday = birthday?.date else { return "NA" }
guard let bday = birthday?.date else {
return NSLocalizedString("No birthday", comment: "User has no birthday")
}
let now = Date()
let calendar = Calendar.autoupdatingCurrent
let dayComps = calendar.dateComponents([.day], from: now, to: bday)
guard let days = dayComps.day else { return "NA" }
guard let days = dayComps.day else {
return NSLocalizedString("No birthday", comment: "User has no birthday")
}
return String(days)
}
private var cancellable: AnyCancellable?
Expand All @@ -42,6 +46,7 @@ final class BirthdayViewModel: ObservableObject {
case .finished:
break
case .failure(let error):
self.birthday = Birthday.noBirthday
print("Error retrieving birthday: \(error)")
}
} receiveValue: { birthday in
Expand Down