Код: Выделить всё
DataSource
Код: Выделить всё
class DataEntry: Codable, Comparable {
var theDate: Date = Date() // To avoid using an optional but still silence compiler
// complaints about no initializer
// Lots of other properties and support code irrelevant to the question snipped for brevity.
}
Код: Выделить всё
class DataSource: Codable {
var theArray: [DataEntry] = Array()
// Several hundred lines of non-relevant support and convenience code chopped
// Return either .theDate from the earliest DataEntry held in theArray, or Date()
// if theArray.first hands back a nil (indicating theArray is unpopulated).
// Either way, I specifically want the returned value to *NOT* be an optional!
func earliest() -> Date {
// First, make certain theArray is sorted ascending by .theDate
theArray.sort {
$0.theDate < $1.theDate
}
// Now that we know theArray is in order, theArray.first?.theDate is the earliest stored date
// - If it exists.
// But since .first hands back an optional, and I specifically DO NOT WANT an optional return from
// .earliest(), I nil-coalesce to set firstDate to Date() as needed.
let firstDate: Date = theArray.first?.theDate ?? Date()
print("firstDate = \(firstDate)")
return firstDate
}
func latest() -> Date {
// gutted for brevity - mostly identical to .earliest()
return lastDate
}
}
Код: Выделить всё
class SelectDateRangeViewController: UIViewController {
@IBOutlet weak var startPicker: UIDatePicker!
@IBOutlet weak var endPicker: UIDatePicker!
// Irrelevant code elided
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let e = theData.earliest()
// Note: Changing the previous line to
// let e = theData.earliest()!
// gets a compile-time error: "Cannot force unwrap value of non-optional type 'Date'"
let l = theData.latest()
// We should now have the earliest and latest dates in theData held in e and l, respectively.
// Print them to the debugger console to verify they're actually what I expect...
print ("e = \(e)")
print ("l = \(l)")
// ...and carry on
startPicker.minimumDate = e //
Подробнее здесь: [url]https://stackoverflow.com/questions/61530178/why-is-my-carefully-designed-to-be-not-optional-return-value-being-treated-lik[/url]