Creating the Line Struct

You are going to create the custom Line type. So far, all of the types that you have created have been classes. In fact, they have been Cocoa Touch subclasses; for example, you have created subclasses of NSObject, UIViewController, and UIView.

Line will be a struct. You have used structs throughout this book – CGRect, CGSize, and CGPoint are all structs. So too are String, Int, Array, and Dictionary. Now you are going to create one of your own.

Create a new Swift file named Line.

In Line.swift, import CoreGraphics and declare the Line struct. Declare two CGPoint properties that will determine the beginning and ending point for the line.

import Foundation
import CoreGraphics

struct Line {
    var begin = CGPoint.zero
    var end = CGPoint.zero
}

Structs

Structs differ from classes in a number of ways:

  • Structs do not support inheritance.

  • Structs get a member-wise initializer if no other initializers are declared. The member-wise initializer takes in an argument for each property within the type. The Line struct, for example, has the member-wise initializer init(begin: CGPoint, end: CGPoint).

  • If all properties have default values and no other initializers are declared, structs also gain an empty initializer (init()) that creates an instance and sets all of the properties to their default value.

  • Perhaps most importantly, structs (and enums) are value types – as opposed to classes, which are reference types.

Value types vs reference types

Value types are types whose values are copied when they are assigned to another instance or passed in the argument of a function. This means that assigning an instance of a value type to another actually assigns a copy of the first instance to the second instance. Value types play an important role in Swift. For example, arrays and dictionaries are both value types. All enums and structs you write are value types as well.

Reference types are not copied when they are assigned to an instance or passed into an argument of a function. Instead, a reference to the same instance is passed. Classes and closures are reference types.

So which do you choose? In general, we suggest starting out with a value type (such as a struct) unless you absolutely know you need the benefits of a reference type. Value types are easier to reason about because you do not need to worry about what happens to an instance when you change values on a copy. If you would like a deeper discussion on this topic, check out Swift Programming: The Big Nerd Ranch Guide.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset