Power of Switch case statements in Swift, Interval matching, type checking, value binding, where clause, tuple, if case let and the pattern matching

In this post we will go through some amazing and useful tips that we can do with the Switch control flow statement.

Some benefits with using Switch statements rather than if

  1. Switch statements are exhaustive, which means you must have to add a case for every possible value to check or you must have a defaultcase.
  2. Switch read the value once and compare with all case, which help to improve the performance.
  3. Switch cases allows the advanced pattern matching which will we see later in this post.

To match a value against a number of cases

switch statusCode {
	case 200:
	// 200 code here
	case 404:
	// 500 code here
	case 500, 501:
	// 500 or 501 code here
	default:
	// default handling code

Extending the functionality

extension Int {
	static let resourseNotFound = 404
	static let serverError = 500
	static let ok = 200
}

switch statusCode {
	case .resourseNotFound:
	// 404 code here
	case serverError:
	// 500 code here
	default:
	// default handling code
}

Interval matching

switch statusCode {
	case 200...201:
	// code here to handle 200, 201
	case 400..499:
	// code here to handle 400 to 499
	case 500..<599:
	// code here to handle 400 to 499
	default:
	// default handling code
}

Type checking

switch discount {
	case is Int:
	// discount is int type
	case let discount as String:
	// discount is String type
	default:
	// default handling code
}

Value Bindings ( name the value(s) matches to the temporary constant(s) )

let point = (x: 10, y:50)

switch frame {
	case (_, let y):
	// somewher on x where the y value is `y`
	case let (x, y)
	// somewhere at `x` and `y`
}

Implement with enum

enum {
	case success
	case error(code: Int)
}

switch error {
	case .success:
	// success here
	case .error(let code):
	// error with status code here
}

Chip in the where clause

enum {
	case success
	case error(code: Int)
}

switch error {
	case .success:
	// success here
	case .error(let code) where code == 404:
	// error with status code 404 here
	case .error(let code) where code == 400:
	// error with status code 400 here
}

with tuple

let frame = (x: 10, y:50, width:100, height: 100)

switch frame {
	case (_, _, let width, _) where width == 100:
	// width is 100 here
	case (_, _, let width, height) where width == height:
	// where height is equal to width
	case .error(let x, let y, let width, let height)
	// any case here
}

If case let

This is to avoid a full switch statement when you only want to match a single case.

if case let .error(code) = response { }

// alternate form 
if case .error(let code) = response { }

// with extra condition check
if case let .error(code) = response, code == 500 { }

// with guard statement
guard case let .error(code) = response {
	return
}

// with for-in loop
for case let code in response {}

// with for-in loop + where clause
for case let code in response where code == 500 {}

Fallthrough

Swift don’t fall through the bottom of each case, the entire switch statement completes as soon as the first matching case is completed. Languages like C requires you to insert an explicit break statement at the end of every switch case to prevent the fallthrough . In Swift it simply causes code execution to move directly to the statements inside the next case.

switch error {
	case .success:
	// success here
	fallthrough

	case .error(let _):
	// failure
	fallthrough

	case default:
	// request finished.
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.