Group Group Group Group Group Group Group Group Group

Programming in Swift: Functions and Types · More Switch Statements | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5429279-programming-in-swift-functions-and-types/lessons/24

Hi :slight_smile:

How come we can use .max just like that? The number is greater than
.max / 2 of what? I think I don’t understand this instruction (line 9) :frowning:

func getDescription(for number: Int) → String {
switch number {
case 0:
return “Zero”
case 1…9:
return “Between 1 and 9”
case let negativeNumber where negativeNumber < 0:
return “Negative”
case _ where number > .max / 2:
return “Very large!”
default:
return “No Description”
}
}

1 Like

@szarik The max property is defined as a static one for the Int type, so you normally call it as a type property using its type name explicitly like this: Int.max.

You can read even more about the whole thing over here:

https://developer.apple.com/documentation/swift/int/1540171-max

You can write the corresponding switch case as follows in this case:

case _ where number > Int.max / 2: return "Very large!"

You can also use type inference since the number parameter in the getDescription(for:) method is declared as an Int argument, so you definitely know that you are comparing two Int values in the associated switch case.

.max uses the Int type implicitly under the hood, so it is simply syntactic sugar and shorthand dot syntax for Int.max.

This is how things are actually done in the video tutorial:

case _ where number > .max / 2: return "Very large!"

This is exactly the default behaviour for enumeration cases too.

You can read even more about this over here:

https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html

The min property is defined as a static one for the Int type as well.

You can read even more about it over here:

https://developer.apple.com/documentation/swift/int/1539485-min

You can easily write a min switch case too which would be very similar actually to the max one either by using the Int type explicitly like this:

case _ where number < Int.min / 2: return "Very small!"

Or by using type inference implicitly instead as follows:

case _ where number < .min / 2: return "Very small!"

Please let me know if you have any more questions or other issues about the whole thing when you get a chance.

Thank you!

1 Like

Thanks @shogunkaramazov ! Now it is much simpler! :slight_smile:
Still being surprised how many things Swift infer…

2 Likes