From 7ebfc795030529120cdceb4ab639b38df57de826 Mon Sep 17 00:00:00 2001 From: fechin Date: Wed, 1 Mar 2023 09:18:32 +0800 Subject: [PATCH] Update example to add guard statement and print statement to demonstrate age calculation --- source/_posts/swift.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/source/_posts/swift.md b/source/_posts/swift.md index c9e1cd9..e69f734 100644 --- a/source/_posts/swift.md +++ b/source/_posts/swift.md @@ -250,18 +250,26 @@ import Foundation let df = DateFormatter() df.dateFormat = "d MMMM yyyy" -var birth = df. date(from: "5 June 1999")! -var age: Int { - Calendar.current - .dateComponents([.year], - from: birth, - to: Date()).year! +guard var birth = df.date(from: "5 June 1999") else { + print("Date is not valid") + return } +var age: Int { + Calendar.current + .dateComponents([.year], + from: birth, + to: Date()).year! +} + +print(age) // 23 +guard let birth2 = df.date(from: "5 June 2002") else { + print("Date is not valid") + return +} +birth = birth2 print(age) // 20 -birth = df.date(from: "5 June 2002")! -print(age) // 17 ``` In the example below, distanceInFeet has a `getter` and a `setter`. Because of the `setter`, the `getter` requires the keyword `get`: