• Swift + Keywords (V 3.0.1)
  • By Jordan Morgan
  • The Nuggets translation Project
  • Translator: Deepmissea
  • Proofread by: YLQ167, oOatuo

Macbook + Paper. A deadly combination

Swift + Keyword (V 3.0.1)

A Tell All

It has been said before, and I will mention it again, that a good workman’s tools are as good as his. When we use these tools meticulously, they will take us where we want to go, or finish the work of our dreams.

I don’t mean that pejoratively, because there’s always a lot to learn. So today, we’ll take a look at each of the keywords in Swift (V 3.0.1), the code it provides for each of us, and the name of the tool we each ordered.

Some are simple, some are obscure, and some are somewhat recognisable. But they’re all worth reading and learning. It’s going to be a long time. Are you ready?

Now, let’s get high

Declaration key

Associatedtype: Provides a placeholder for a type, usually as part of a protocol. This type is unknown until the protocol is complied with.

protocol Entertainment { associatedtype MediaType } class Foo : Entertainment {typeAlias MediaType = String // Can be any type that meets the requirements? }Copy the code

Class: A common and flexible infrastructure for building program code. Similar to struct except:

  • Inheritance. Allows a class to inherit features from another class.
  • Type conversion. Allows you to examine and interpret the type of an instance of a class at run time.
  • Destructor. Allows an instance of a class to release any resources it allocates.
  • Reference counting. Allows instances of a class to have multiple references.
class Person
{
    var name:String
    var age:Int
    var gender:String
}Copy the code

Deinit: called immediately before the class instance is released.

class Person
{
    var name:String
    var age:Int
    var gender:String

    deinit
    {
        // Release from the pile and unload here.}}Copy the code

Enum: Defines a common type for a set of related values and enables you to use those values in a type-safe way in your code. In Swift, they belong to the first category and can use features that are often supported only by classes in other languages.

enum Gender
{
    case male
    case female
}Copy the code

Extension: Allows you to add new functionality to an existing class, structure, enumeration, or protocol.

class Person
{
    var name:String = ""
    var age:Int = 0
    var gender:String = ""
}

extension Person
{
    func printInfo()
    {
        print("My name is \(name), I'm \(age) years old and I'm a \(gender).")}}Copy the code

Fileprivate: Access control structure that limits scope to source files.

class Person
{
    fileprivate var jobTitle:String = ""
}

extension Person
{

    // If you use a "private" declaration, it will not compile.
    func printJobTitle()
    {
        print("My job is \(jobTitle)")}}Copy the code

Func: Executes a specific self-contained block of code.

func addNumbers(num1:Int, num2:Int) -> Int
{
    return num1+num2
}Copy the code

Import: Exposes a built framework or application as a unit to a specified binary file.

import UIKit

// Now all UIKit code can be called
class Foo {}Copy the code

Init: The process of constructing an instance of a class, structure, or enumeration.

class Person 
{
    init()
    {
        // Set the default values here, etc.}}Copy the code

Inout: Pass a value to a function, then modify it, and it will be returned to its original location in place of the original value. Applies to reference types and value types.

func dangerousOp(_ error:inout NSError?)
{
    error = NSError(domain: "".code: 0.userInfo: ["":""])}var potentialError:NSError?

dangerousOp(&potentialError)

// Now potentialError is initialized and is no longer nilCopy the code

Internal: An access control structure that allows an entity to be used in any source file in which it defines a module, but not in source files outside of it.

class Person
{
    internal var jobTitle:String = ""
}

let aPerson = Person()
aPerson.jobTitle = "This can set anywhere in the application"Copy the code

Let: Define an immutable variable.

let constantString = "This cannot be mutated going forward"Copy the code

Open: Access control structure that allows objects to be accessed or subclassed outside the defined module. For members, external modules are also accessible and overridden.

open var foo:String? // Both the inside and outside of an application can be accessed or overridden, which is a common access control character when writing a frameworkCopy the code

Operator: A special symbol or phrase used to check, change, or combine values.

// The "-" unary operator reduces the value of the target
let foo = 5
let anotherFoo = -foo // anotherFoo is now -5

// "+" combines two values
let box = 5 + 3


// the "&&" logical operator is used to combine two Boolean values
if didPassCheckOne && didPassCheckTwo


// A ternary operator containing three values?
let isLegalDrinkingAgeInUS:Bool = age >= 21 ? true : falseCopy the code

Private: Access control structure that limits the scope of an entity to its declared location.

class Person
{
    private var jobTitle:String = ""
}

extension Person
{
    JobTitle is only scoped in the Person class
    func printJobTitle()
    {
        print("My job is \(jobTitle)")}}Copy the code

Protocol: A blueprint that defines classes, attributes, and other requirements suitable for a particular task or part of a function.

protocol Blog { var wordCount:Int { get set } func printReaderStats() } class TTIDGPost : Blog {var wordCount:Int init(wordCount:Int) {self.wordCount = wordCount} func printReaderStats() {// Print some statistics}}Copy the code

Public: Access control structure that allows objects to be accessed or subclassed within the defined module, and members to be accessed and overridden only within the defined module.

public var foo:String? // It can be overwritten or overwritten anywhere inside the program, but not outside.Copy the code

Static: Defines the type’s own calling method. It is also used to define its static members.

class Person
{
    var jobTitle:String?

    static func assignRandomName(_ aPerson:Person)
    {
        aPerson.jobTitle = "Some random job"}}let somePerson = Person()
Person.assignRandomName(somePerson)
//somePerson.jobTitle is now "Some random job"Copy the code

Struct: A generic and flexible infrastructure for building program code that also provides initialization methods for members. Unlike classes, they are always copied when passed in code, without automatic reference counting being enabled. In addition, they cannot:

  • Use inheritance.
  • Do type conversions at run time.
  • Own or use a destructor.
struct Person
{
    var name:String
    var age:Int
    var gender:String
}Copy the code

Subscript: A shortcut to access a collection, list, or sequence.

var postMetrics = ["Likes":422."ReadPercentage":0.58."Views":3409]
let postLikes = postMetrics["Likes"]Copy the code

Typealias: Alias the name of an existing type.

typealias JSONDictionary = [String: AnyObject]

func parseJSON(_ deserializedData:JSONDictionary){}Copy the code

Var: Defines a mutable variable.

var mutableString = ""
mutableString = "Mutated"Copy the code

The keyword in the statement

Break: To end a loop, or in if, switch.

for idx in 0..3.
{
    if idx % 2= =0
    {
        //Exits the loop on the first even value
        break}}Copy the code

Case: a statement that evaluates and compares the value to the type provided by the switch.

let box = 1

switch box
{
case 0:
    print("Box equals 0")
case 1:
    print("Box equals 1")
default:
    print("Box doesn't equal 0 or 1")}Copy the code

Continue: Terminates the current iteration of a loop statement, but does not terminate the continuation of the loop statement.

for idx in 0..3.
{
    if idx % 2= =0
    {
        //Immediately begins the next iteration of the loop
        continue
    }

    print("This code never fires on even numbers")}Copy the code

Default: Used to override values not explicitly defined in the case structure.

let box = 1

switch box
{
case 0:
    print("Box equals 0")
case 1:
    print("Box equals 1")
default:
    print("Covers any scenario that doesn't get addressed above.")}Copy the code

Defer: To execute the code before program control is transferred out of scope.

func cleanUpIO()
{
    defer
    {
        print("This is called right before exiting scope")}//Close out file streams,etc.
}Copy the code

Do: A leading statement used to handle errors in a piece of code.

do
{
    try expression
    //statements
}
catch someError ex
{
    //Handle error
}Copy the code

Else: Used in conjunction with an if statement to execute part of the code when the condition is true and another part when the same condition is false.

if 1 > val
{
    print("val is greater than 1")}else
{
    print("val is not greater than 1")}Copy the code

Fallthrough: In switch statements, explicitly allows one case to proceed to the next.

let box = 1

switch box
{
case 0:
    print("Box equals 0")
    fallthrough
case 1:
    print("Box equals 0 or 1")
default:
    print("Box doesn't equal 0 or 1")}Copy the code

For: Iterates over a sequence, such as a range of numbers, items in an array, or characters in a string. Pair with the in keyword

for _ in 0.. <3 { print ("This prints 3 times")}Copy the code

Guard: Transfers program control out of scope if one or more conditions are not met, while unpacking any optional type.

private func printRecordFromLastName(userLastName: String?). { guardletname = userLastName, userLastName ! ="Null" else
    {
        //Sorry Bill Null, find a new job
        return
    }

    //Party on
    print(dataStore.findByLastName(name))
}Copy the code

If: Executes code based on the value of one or more conditions.

if 1 > 2
{
    print("This will never execute")}Copy the code

In: Iterates over a sequence, such as a range of numbers, items in an array, or characters in a string. Pair with the for keyword

for _ in 0.. <3 { print ("This prints 3 times")}Copy the code

Repeat: Executes the contents of the loop once before considering the loop condition.

repeat
{
    print("Always executes at least once before the condition is considered")}while 1 > 2Copy the code

Return: Immediately interrupts the control flow of the current context, and returns the resulting value (if present).

func doNothing()
{
    return //Immediately leaves the context

    let anInt = 0
    print("This never prints \(anInt)")}Copy the code

and

func returnName() -> String?
{
    return self.userName //Returns the value of userName
}Copy the code

Switch: Considers a value and compares it with several possible matching patterns. The appropriate code block is then executed based on the first pattern successfully matched.

let box = 1

switch box
{
case 0:
    print("Box equals 0")
    fallthrough
case 1:
    print("Box equals 0 or 1")
default:
    print("Box doesn't equal 0 or 1")}Copy the code

Where: The type of the association must conform to a specific protocol or be the same as some specific parameter type. It is also used to provide an additional control condition to determine whether a pattern conforms to a control expression. The WHERE clause can be used in multiple contexts, and these examples are the primary uses of WHERE as a clause and pattern matching.

protocol Nameable
{
    var name:String {get set}
}

func createdFormattedName<T:Nameable>(_ namedEntity:T) -> String where T:Equatable
{
    //Only entities that conform to Nameable which also conform to equatable can call this function
    return "This things name is " + namedEntity.name
}Copy the code

As well as

for i in 0...3 where i % 2= =0
{
    print(i) //Prints 0 and 2
}Copy the code

While: Execute a set of statements until the condition becomes’ false’.

whilefoo ! = bar { print("Keeps going until the foo == bar")}Copy the code

Expression and type keywords

Any: Can be used to represent instances of Any type, including function types.

var anything = [Any]()

anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) - >String in "Passed in \(foo)"})Copy the code

As: Type conversion operator that attempts to convert values to different, expected, and specific types.

var anything = [Any]()

anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) - >String in "Passed in \(foo)" })

let intInstance = anything[1] as? IntCopy the code

or

var anything = [Any]()

anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) - >String in "Passed in \(foo)" })

for thing in anything
{
    switch thing
    {
    case 0 as Int:
        print("It's zero and an Int type")
    case let someInt as Int:
        print("It's an Int that's not zero but \(someInt)")
    default:
        print("Who knows what it is")}}Copy the code

Catch: If an error is thrown in a do clause, it matches how the error will be handled based on the catch clause. Excerpted from my previous article on error handling for Swift.

do
{
    try haveAWeekend(4)}catch WeekendError.Overtime(letHoursWorked) {print(" You worked \(hoursWorked) more than You should have ")}catchWeekendError. WorkAllWeekend {print (" You worked48 hours :0")}catch
{
    print(“Gulping the weekend exception”)
}Copy the code

False: One of two values used in Swift to represent the logical type – Boolean type, which is not true.

let alwaysFalse = false
let alwaysTrue = true

if alwaysFalse { print("Won't print, alwaysFalse is false 😉")}Copy the code

Is: Type checking operator used to identify whether an instance is of a specific type.

class Person {}
class Programmer : Person {}
class Nurse : Person {}

let people = [Programmer(), Nurse()]

for aPerson in people
{
    if aPerson is Programmer
    {
        print("This person is a dev")
    }
    else if aPerson is Nurse
    {
        print("This person is a nurse")
    }
}Copy the code

Nil: Represents any type of stateless value in Swift. Unlike Nil in Objective-C, it’s a pointer to an object that doesn’t exist.

class Person{}
struct Place{}

//Literally any Swift type or instance can be nil
var statelessPerson:Person? = nil
var statelessPlace:Place? = nil
var statelessInt:Int? = nil
var statelessString:String? = nilCopy the code

Rethrows: Indicates that the function throws an error only if an argument of one of its function types throws an error.

func networkCall(onComplete:() throws -> Void) rethrows
{
    do
    {
        try onComplete()
    }
    catch
    {
        throw SomeError.error
    }
}Copy the code

Super: Exposed access to a superclass property, method, or alias.

class Person { func printName() { print("Printing a name. ") } } class Programmer : Person { override func printName() { super.printName() print("Hello World!" ) } } let aDev = Programmer() aDev.printName() //"Printing a name. Hello World!"Copy the code

Self: The implied property of each type instance, which is exactly equal to the instance itself. Useful in distinguishing function parameter names from attribute names.

class Person
{
    func printSelf()
    {
        print("This is me: \(self)")}}let aPerson = Person()
aPerson.printSelf() //"This is me: Person"Copy the code

Self: In the protocol, represents the type that ultimately conforms to the given protocol.

protocol Printable
{
    func printTypeTwice(otherMe:Self)
}

struct Foo : Printable
{
    func printTypeTwice(otherMe: Foo)
    {
        print("I am me plus \(otherMe)")}}let aFoo = Foo()
let anotherFoo = Foo()

aFoo.printTypeTwice(otherMe: anotherFoo) //I am me plus Foo()Copy the code

Throw: Throws an error directly from the current context.

enum WeekendError: Error
{
    case Overtime
    case WorkAllWeekend
}

func workOvertime () throws
{
    throw WeekendError.Overtime
}Copy the code

Throws: Indicates that a function, method, or initialization method may throw an error.

enum WeekendError: Error
{
    case Overtime
    case WorkAllWeekend
}

func workOvertime () throws
{
    throw WeekendError.Overtime
}

//"throws" indicates in the function's signature that I need use try, try? or try!
try workOvertime()Copy the code

True: One of two values used in Swift to represent the logical type – Boolean type, representing true.

let alwaysFalse = false
let alwaysTrue = true

if alwaysTrue { print("Always prints")}Copy the code

Try: indicates that the following function may throw an error. There are three different usages: try, try? And the try! .

let aResult = try dangerousFunction() //Handle it, or propagate it
let aResult = try! dangerousFunction() //This could trap
if let aResult = try? dangerousFunction() //Unwrap the optionalCopy the code

Use patterns in keywords

_ : wildcard, matches and ignores any value.

for _ in 0.. <3
{
    print("Just loop 3 times, index has no meaning")}Copy the code

another use

let _ = Singleton() //Ignore value or unused variableCopy the code

Keyword is used in

#available: Conditions for if, while, and GUARD statements to query the availability of the API at run time, depending on the particular platform.

if #available(iOS 10, *)
{
    print("iOS 10 APIs are available")
}Copy the code

#colorLiteral: Playground literal that returns an interactive color selector to assign to a variable.

let aColor = #colorLiteral //Brings up color pickerCopy the code

#column: A special literal expression that returns the number of columns at its starting position.

class Person
{
    func printInfo()
    {
        print("Some person info - on column \(#column)")}}let aPerson = Person()
aPerson.printInfo() //Some person info - on column 53Copy the code

#else: Compile conditional control statements that allow a program to conditionally compile some specified code. Used in conjunction with the # if statement, part of the code is executed when the condition is true and another part is executed when the same condition is false.

#if os(iOS)
    print("Compiled for an iOS device")
#else
    print("Not on an iOS device")
#endifCopy the code

#elseif: Conditional compilation control statement that allows a program to conditionally compile specified code. Used in conjunction with the # if statement, this part of the code executes when the given condition is true.

#if os(iOS)
    print("Compiled for an iOS device")
#elseif os(macOS)
    print("Compiled on a mac computer")
#endifCopy the code

#endif: Conditional compilation control statement that allows a program to conditionally compile some specified code. Used to mark the end of code that requires conditional compilation.

#if os(iOS)
    print("Compiled for an iOS device")
#endifCopy the code

#file: a special literal expression that returns the name of the file.

class Person
{
    func printInfo()
    {
        print("Some person info - inside file \(#file)")}}let aPerson = Person()
aPerson.printInfo() //Some person info - inside file /*file path to the Playground file I wrote it in*/Copy the code

#fileReference: Playground literal, which returns a selector to select the file and then returns it as an instance of NSURL.

let fontFilePath = #fileReference //Brings up file pickerCopy the code

# the function: A special literal expression that returns the name of a function, if in a method it returns the name of the method, if in a getter or setter for a property it returns the name of the property, if in a special member such as init or subscript it returns the keyword, if at the top of the file, It returns the name of the current module.

class Person
{
    func printInfo()
    {
        print("Some person info - inside function \(#function)")}}let aPerson = Person()
aPerson.printInfo() //Some person info - inside function printInfo()Copy the code

#if: conditional compilation control statement that allows a program to conditionally compile some specified code. Determine whether to execute code based on one or more criteria.

#if os(iOS)
    print("Compiled for an iOS device")
#endifCopy the code

#imageLiteral: playground literal, which returns a selector to select the image and then returns it as a UIImage instance.

let anImage = #imageLiteral //Brings up a picker to select an image inside the playground fileCopy the code

#line: A special literal expression that returns the number of lines at its location.

class Person
{
    func printInfo()
    {
        print("Some person info - on line number \(#line)")}}let aPerson = Person()
aPerson.printInfo() //Some person info - on line number 5Copy the code

#selector: An expression that forms an Objective-C selector, which uses static checking to ensure that the method exists and that it is also exposed to Objective-C.

//Static checking occurs to make sure doAnObjCMethod exists
control.sendAction(#selector(doAnObjCMethod), to: target, forEvent: event)Copy the code

#sourceLocation: Line control statement used to specify the number of lines and the name of the file, which may be different from the number of lines and names of the source code being compiled. Suitable for diagnostics and debugging when changing source code location.

#sourceLocation(file:"foo.swift", line:6) //Reports new values print(#file) print(#line) //This resets the source code location back to the default values  numbering and filename #sourceLocation() print(#file) print(#line)Copy the code

Keywords in a particular context

  • If these keywords are used outside of their respective contexts, they can actually serve as identifiers

Associativity: Specifies how operators of the same priority level can be grouped together without left, right, or None grouping parentheses.

infix operator ~ { associativity right precedence 140 }
4 ~ 8Copy the code

Convenience: a secondary initializer in a class that eventually delegates the initialization of an instance to a specific initializer.

class Person
{
    var name:String


    init(_ name:String)
    {
        self.name = name
    }


    convenience init()
    {
        self.init("No Name")}}let me = Person()
print(me.name)//Prints "No Name"Copy the code

Dynamic: Indicates that access to this member or function is never inline or virtualized by the compiler, which means that access to this member is always distributed dynamically (rather than statically) using the Objective-C runtime.

class Person
{
    //Implicitly has the "objc" attribute now too
    //This is helpful for interop with libs or
    //Frameworks that rely on or are built
    //Around Obj-C "magic" (i.e. some KVO/KVC/Swizzling)
    dynamic var name:String?
}Copy the code

DidSet: Property observation, called immediately after the property stores a value.

var data = [1.2.3]
{
    didSet
    {
        tableView.reloadData()
    }
}Copy the code

Final: Prevents methods, properties, or subscripts from being inherited.

final class Person {}
class Programmer : Person {} //Compile time errorCopy the code

Get: Returns the value given by the member. It is also used to calculate properties, and other properties and values can be obtained indirectly.

class Person
{
    var name:String
    {
        get { return self.name }
        set { self.name = newValue}
    }

    var indirectSetName:String
    {
        get
        {
            if let aFullTitle = self.fullTitle
            {
                return aFullTitle
            }
            return ""
        }

        set (newTitle)
        {
            //If newTitle was absent, newValue could be used
            self.fullTitle = "\(self.name) :\(newTitle)"}}}Copy the code

Infix: A specific operator used between two targets. If a new global operator is defined as a central operator, it also requires a priority group between members.

let twoIntsAdded = 2 + 3Copy the code

Indirect: Indicates that an enumeration takes an instance of another enumeration as an associated value of one or more enumerations.

indirect enum Entertainment
{
    case eventType(String)
    case oneEvent(Entertainment)
    case twoEvents(Entertainment, Entertainment)
}

let dinner = Entertainment.eventType("Dinner")
let movie = Entertainment.eventType("Movie")

let dateNight = Entertainment.twoEvents(dinner, movie)Copy the code

Lazy: The initial value of the attribute is computed the first time it is used.

class Person
{
    lazy var personalityTraits = {
        //Some crazy expensive database hit
        return ["Nice"."Funny"]}} ()let aPerson = Person()
aPerson.personalityTraits //Database hit only happens now once it's accessed for the first timeCopy the code

Left: Specifies that operators are associated from left to right, so that groups of the same priority are grouped correctly without grouping parentheses.

//The "-" operator's associativity is left to right
102 -4 - //Logically grouped as (10-2) - 4Copy the code

Mutating: Allows modification of properties of a structure or enumeration in a specific method.

struct Person
{
    var job = ""

    mutating func assignJob(newJob:String)
    {
        self = Person(job: newJob)
    }
}

var aPerson = Person()
aPerson.job / / ""

aPerson.assignJob(newJob: "iOS Engineer at Buffer")
aPerson.job //iOS Engineer at BufferCopy the code

None: The operator provides no correlation, which limits the interval between occurrences of operators of the same precedence.

//The "<" operator is a nonassociative operator
1 < 2 < 3 //Won't compileCopy the code

Nonmutating: SETters that specify members do not modify the instance it contains, but can serve other purposes.

enum Paygrade
{
    case Junior, Middle, Senior, Master

    var experiencePay:String?
    {
        get
        {
            database.payForGrade(String(describing:self))
        }

        nonmutating set
        {
            if let newPay = newValue
            {
                database.editPayForGrade(String(describing:self), newSalary:newPay)
            }
        }
    }
}

let currentPay = Paygrade.Middle

//Updates Middle range pay to 45k, but doesn't mutate experiencePay
currentPay.experiencePay = "$45000"Copy the code

Optional: Describes optional methods in the protocol. These methods need not be implemented by protocol-compliant types.

@objc protocol Foo
{
    func requiredFunction()
    @objc optional func optionalFunction()
}

class Person : Foo
{
    func requiredFunction()
    {
        print("Conformance is now valid")
    }
}Copy the code

Override: indicates that a subclass will provide its own custom implementation of instance methods, class methods, instance attributes, class attributes, or subscripts, or it will inherit from its parent class.

class Person { func printInfo() { print("I'm just a person!" ) } } class Programmer : Person { override func printInfo() { print("I'm a person who is a dev!" ) } } let aPerson = Person() let aDev = Programmer() aPerson.printInfo() //I'm just a person! aDev.printInfo() //I'm a person who is a dev!Copy the code

Postfix: Specifies the operator after the target on which it operates.

var optionalStr:String? = "Optional"
print(optionalStr!)Copy the code

Precedence: Indicates that the precedence of one operator is higher than that of other operators. Therefore, they are used first.

infix operator ~ { associativity right precedence 140 }
4 ~ 8Copy the code

Prefix: Specifies that the operator precedes the target of its operation.

var anInt = 2
anInt = -anInt //anInt now equals -2Copy the code

Required: Forces the compiler to ensure that each subclass must implement a given initializer.

class Person
{
    var name:String?


    required init(_ name:String)
    {
        self.name = name
    }
}


class Programmer : Person
{
    //Excluding this init(name:String) would be a compiler error
    required init(_ name: String)
    {
        super.init(name)
    }
}Copy the code

Right: Specifies that operators are associated in right-to-left order, so that groups of the same priority are grouped correctly without grouping parentheses.

//The "??" operator's associativity is right to left
var box:Int?
var sol:Int? = 2


let foo:Int = box ?? sol ?? 0 //Foo equals 2Copy the code

Set: Gets the value of a member as its new value. It can also be used to evaluate properties and indirectly set other properties and values. If a setter for a calculated property does not define a name to represent the newValue to be set, the default name for the newValue is newValue.

class Person
{
    var name:String
    {
        get { return self.name }
        set { self.name = newValue}
    }


    var indirectSetName:String
    {
        get
        {
            if let aFullTitle = self.fullTitle
            {
                return aFullTitle
            }
            return ""
        }


        set (newTitle)
        {
            //If newTitle was absent, newValue could be used
            self.fullTitle = "\(self.name) :\(newTitle)"}}}Copy the code

Type: refers to any Type, including class Type, structure Type, enumeration Type, and protocol Type.

class Person {}
class Programmer : Person {}


let aDev:Programmer.Type = Programmer.selfCopy the code

unowned: In circular references, one instance refers to another and is not held strongly while the other instance has the same lifetime or longer.

class Person
{
    var occupation:Job?
}


//Here, a job never exists without a Person instance, and thus never outlives the Person who holds it.
class Job
{
    unowned let employee:Person


    init(with employee:Person)
    {
        self.employee = employee
    }
}Copy the code

Weak: In circular references, an instance refers to another instance and is not strongly held on the other instance when it has a short lifetime.

class Person
{
    var residence:House?
}


class House
{
    weak var occupant:Person?
}


var me:Person? = Person()
varmyHome:House? = House() me! .residence = myHome myHome! .occupant = me me = nil myHome! .occupant//Is now nilCopy the code

WillSet: Property observation, called just before the property is about to store a value.

class Person
{
    var name:String?
    {
        willSet(newValue) {print("I've got a new name, it's \(newValue)!")}}}let aPerson = Person()
aPerson.name = "Jordan" //Prints out "I've got a new name, it's Jordan!" right before name is assigned toCopy the code

Final thoughts

Shout!

This is an interesting creation. I chose something to write about that I hadn’t really thought through before, but I think these tips don’t need to be memorized like a list of exams.

Better yet, keep this list with you at all times. Keep it stimulating your brain waves so that when you need to use a particular keyword, you’ll know it and use it.

See you next time – thanks for reading ✌️.