W1412 Constructors

From Coder Merlin
Revision as of 21:41, 28 February 2019 by Chukwuemeka-tinashe (talk | contribs) (Created page with "DRAFT ICON = Initialization = == Research == Initialization is the process of preparing an instance of a class, structure, or enumeration type for u...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

DRAFT ICON


Initialization[edit]

Research[edit]

Initialization is the process of preparing an instance of a class, structure, or enumeration type for use. It requires that we provide an initial value for each stored property. We may also perform any other additional initialization that we require.

Experiment[edit]

Create a directory within your "project" directory.

cd ~/projects
mkdir project-1412
cd project-1412

Edit a new file named "main.swift"

emacs main.swift

For this project you'll repeatedly edit the same file. It's probably easiest to test this file within emacs by typing: M-& (async-shell-command) and observing the results. For each question, be sure to understand the behavior before proceeding to the next question. It will be helpful to record your answers and reasoning for later review.

Oxygen480-actions-help-hint.svg Helpful hint: The async-shell-command can be executed with Alt-Shift-7. The command to execute each time is: swift main.swift

func doIt(a:Int, b:Int) -> Int {
    return a - b
} //

let a : Int = 7
let b : Int = 8
let c = doIt(a:Int, b:Int)
print(c)

What is output? (Ignore whitespace)

-1
Compile or runtime error
1


Key Concepts[edit]

  • Initialization is the process of preparing an instance of a class, structure, or enumeration type for use.
    • Initialization requires that we provide an initial value for each stored property.
  • Initialization is handled by defining initializers.
  • Unlike functions and methods, initializer do not return a value.
  • Initial values for stored properties may be:
    • Set within an initializer, or
    • by setting a default value value when the property is defined
  • The simplest initializer is simply defined as init(), with no parameters. Note that is must be called init.
  • As with other functions and methods, a parameter list may be provided.
  • Because the initializer must be called init, argument labels play a crucial role for specifying the correct initializer.
  • Constant properties may be assigned at any point during initialization, but once assigned, may not be further modified.