iOS Notes 51: How to set a time-based dynamic greeting message? [Swift 5]

Kuray Ogun
FreakyCoder Software Blog

--

Dynamic Greeting Message on Swift 5

Nowadays, we can see numerous example of the greeting message on the top-left of the applications with our name.

Good morning, Kuray

Good afternoon, Kuray

and such like that.

It changes dynamically depends on your time zone.

Here is how to do it easily without any library at all.

Cleaner Version:

Code:

func greetingLogic() -> String {
let hour = Calendar.current.component(.hour, from: Date())

let NEW_DAY = 0
let NOON = 12
let SUNSET = 18
let MIDNIGHT = 24

var greetingText = "Hello" // Default greeting text
switch hour {
case NEW_DAY..<NOON:
greetingText = "Good Morning"
case NOON..<SUNSET:
greetingText = "Good Afternoon"
case SUNSET..<MIDNIGHT:
greetingText = "Good Evening"
default:
_ = "Hello"
}

return greetingText
}

Gist:

NSDate Version:

Code:

func greetingLogic() -> String {
let date = NSDate()
let calendar = NSCalendar.current
let currentHour = calendar.component(.hour, from: date as Date)
let hourInt = Int(currentHour.description)!

let NEW_DAY = 0
let NOON = 12
let SUNSET = 18
let MIDNIGHT = 24

var greetingText = "Hello" // Default greeting text
if hourInt >= NEW_DAY && hourInt <= NOON {
greetingText = "Good Morning"
}
else if hourInt > NOON && hourInt <= SUNSET {
greetingText = "Good Afternoon"
}
else if hourInt > SUNSET && hourInt <= MIDNIGHT {
greetingText = "Good Evening"
}

return greetingText
}

Gist:

As you can see, we simply get the current date and current hour by NSDate. Then we simply cast the `currentHour` to Int and we got the 24-hour integer current hour.

Of course, this is just an example, you can change the greeting text and current hour range depends on your use-case.

That’s it :)

Have fun!

--

--