I tried to describe how to specify the range of conditions in the switch statement. I thought that I could only set a specific value for the condition of the switch statement, so I will leave it in the sense of looking back on my own.
The switch statement switches the instruction to be executed according to the value of the control expression.
ViewController.swift
switch control type{
case Condition 1:
//Processing when condition 1 is met
case Condition 2:
//Processing when condition 2 is met
default:
//What to do if none of the conditions are met
}
There is no range in the condition and you can describe a specific one without any problem, but what should you do if you want to replace the following if statement with a switch statement?
ViewController.swift
let number: Int!
if number > 0 {
//Processing when number is positive
} else if number < 0 {
//Processing when number is negative
} else {
//Processing when number is 0
}
In such a case, use * Int.min * or * Int.max *.
Int.min represents the minimum possible value of the integer type, and Int.max represents the maximum possible value of the integer type.
If you think of the maximum and minimum values of integers, you can think of + ∞ and −∞, but the data are different.
The maximum value of the integer is 9223372036854775807 and the minimum value is -9223372036854775807.
Since the digits are huge, you can think of them as + ∞ and -∞.
So, I will make a switch statement using this.
[Addition] When the random range is all integer type, Int.max will be outside the range of positive integers in 1 .. <Int.max
, so 1 ... Int.max
Fixed
ViewController.swift
let number = Int.random(in: -100...100)
switch number{
case 1...Int.max:
//Processing when number is positive
//[Postscript]1..<Int.For max Int.max is out of range
case Int.min..<0:
//Processing when number is negative
default:
//Processing when number is 0
}
You can also execute it when you want to specify the range without using Int.max. If no processing is performed, it will be interrupted with break.
ViewController.swift
let number = Int.random(in: 0...10)
switch number{
case 1...5:
//number is 1~Processing at 5
case 6...10:
//number is 6~Processing at 10
default: break
}
I myself had solved it only with the if statement without using the switch statement so much, so There may be a mistake in the content. In that case, thank you for pointing out.
This article was written with reference to the following information.
-[Supplementary Revision 3rd Edition] Introduction to Swift Practice
Recommended Posts