{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
Swift - Type Aliases
Summary
This article talks about using a different name to refer to a type, by using typealias.
 
Table of Contents

Type Aliases

Type alias with tuples

Different Environments

Type Aliases in closures

Type Aliasing with Nested Types

 
Article Series
Previous Article:
Test Your Knowledge: Swift - Tuples
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Type Aliases

Type Aliases

Type Alias is a way of naming an existing type to some other name. For this, the keyword typealias is used. Let’s say, you are keeping different types of scores in a game. They all are going to be of type Int. However, making them a type of Score would make the code much more readable. However, Score might not have to be a custom class or struct, it can just be an Int. And, typealias is the easiest and cleanest way to achieve that.

Or, in your networking code, while a port is an Int, say, Port can be typealiased to Int.

typealias Score = Int

var levelScore: Score
var currentScore: Score
var gameScore: Score

// The above are same as
var levelScore: Int
var currentScore: Int
var gameScore: Int
// But the type Score might make more sense in this context

// You can use these variables just like they are Int
levelScore = 100
gameScore = 1000

// Typealias Port to Int
typealias Port = Int
var serversAndPorts = [server: HTTPServer, port: Port]
// A dictionary that contains servers and ports.

// A URL string can be type aliased to String
typealias URL = String
// Now URL strings can use the type name URL, instead of String

Type alias with tuples

You can conveniently typealias the tuple types you commonly use - to provide more context to what you are using it for.

typealias Point = (Int, Int)
typealias ErrorMessage = (Int, String)
 
var point: Point
point = (20,20)

var error: ErrorMessage
error = (404, “Not Found”)

Different Environments

If your app supports multiple operating systems, say, iOS and OS X, you can use typealias to use the same name in your code for differently named types that behave similarly. For example, most of the UI classes in iOS (UIKit) are prefixed with UI; and most of UI classes are prefixed with NS on OS X (AppKit).

If you were using UIEdgeInsets class in UIKit or NSEdgeInsets class in AppKit, they provide similar functionality (these are distance values for top, left, right, bottom to shrink/expand the frame of a view accordingly) - you can typealias it to just EdgeInsets.

#if os(iOS) || os(tvOS)
import UIKit
typealias EdgeInsets = UIEdgeInsets

#else
import AppKit
typealias EdgeInsets = NSEdgeInsets

#endif

// Here you can use the type name EdgeInsets,
// and the type (struct here) that is appropriate for the OS
// will be used.

// For example, on iOS, both the following are similar
var edgeInsets = EdgeInsets(top: 1.0, left: 2.0, bottom: 1.0, right: 2.0)
var edgeInsets2 = UIEdgeInsets(top: 1.0, left: 2.0, bottom: 1.0, right: 2.0)

// Their dynamic and static types are same — UIEdgeInsets (on iOS)
print(edgeInsets.dynamicType)
print(edgeInsets2.dynamicType)
print(EdgeInsets.self) // Static type
// All three above print UIEdgeInsets

// You can also use Mirror — to get the reflection on any of these instances
let edgeInsetsMirror = Mirror(reflecting: edgeInsets)
print(edgeInsetsMirror.subjectType)
// prints UIEdgeInsets

let edgeInsets2Mirror = Mirror(reflecting: edgeInsets2)
print(edgeInsets2Mirror.subjectType)
// prints UIEdgeInsets

The same exact code that uses the EdgeInsets above (not the UIEdgeInsets) on OS X will produce the class NSEdgeInsets when Mirror is used for reflection or dynamic type is obtained via dynamicType or static type is obtained via self on the type itself (EdgeInsets).

Type Aliases in closures

Type Aliases are used a lot in aliasing the closures. Lot of closures have long signatures (closures are functions that can be passed around; in fact functions are closures). So, you don’t need to repeat that closure signature each time you use it.

// Here is a closure that takes NSURLRequest and NSHTTPURLResponse as input
// parameters and returns whether that request is valid or not
typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult

// Let’s say this closure is passed to a method which then reports the error
func validate(validation: Validation) -> NSError {
  return validation(self.request, self.response)
}

// Without typealias, the method declaration would have been much longer and unwieldy
fun validate(validation: (NSURLRequest?, NSHTTPURLResponse) -> validationResult) -> NSError {

}

Into the validate func, different Validation closures can be passed to get the error; Or, there can be different validate methods.

You can also type alias to the nested types. In Swift, you can nest types as many levels deep as you need. You can have a struct within another struct and then there is a struct embedded in that one.

Type Aliasing with Nested Types

For example, String has a nested type called CharacterView. This CharacterView struct gives the collection of characters in the String. And within CharacterView, there is a struct called Index, which gives the position of a character. In order to refer to the Index struct, you can use String.CharacterView.Index - and that also can be type aliased.

typealias StringIndex = String.CharacterView.Index
// Use that type to declare variables to pass the position of characters

Take a Quick Quiz on this Article

1. How do use an alternate type name Score that is just an integer?



: The integer type in Swift is Int
Question 1 of 5
Article Series
Previous Article:
Test Your Knowledge: Swift - Tuples
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Type Aliases
Bookmark and Share This

More Articles With Similar Tags
icon-swift-test.jpg
Tags: typealias, types
Test on using Type Aliases in Swift.
icon-swift-article.jpg
Tags: bool, types, swift
This article discusses the boolean types in Swift and contrasts with how these types are used in C and Objective-C.
icon-swift-test.jpg
Tags: bool, types, swift
Test on Boolean Types in Swift.
icon-swift-article.jpg
Tags: int, types, swift
This article goes through the usage of various integer types in Swift (including Int and UInt).
icon-swift-test.jpg
Tags: int, types, swift
Test on Integer types in Swift.
About  Contact  Privacy Policy  Site Map