Difference between revisions of "Swift Live Reference"

From Coder Merlin
(Added basic page structure.)
 
(Added switch statement.)
Line 31: Line 31:
</syntaxhighlight>
</syntaxhighlight>
==== switch ====
==== switch ====
<syntaxhighlight lang="swift">
switch n {
    case 0:
        print("n is zero")
    case 1:
        print("n is one")
    default:
        print("n is neither one nor zero")
}
</syntaxhighlight>
=== Loops ===
=== Loops ===
Loops are used to repeat a segment of code until a condition is met.
Loops are used to repeat a segment of code until a condition is met.

Revision as of 17:36, 5 March 2022

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Comments[edit]

Comments are used by humans to document code for other humans. They have no effect on the program itself.

Single-line comments[edit]

// single-line comments begin with two slashes

Multi-line comments[edit]

/* multi-line comments begin with slash-star
   and continue 
   and continue
   until a closing star-slash */

Control Structures[edit]

Control structures are used to alter the otherwise sequential flow of a program.

Conditionals[edit]

Conditionals are used to execute a segment of code based upon a condition being met.

if[edit]

if n < 10 {
    print("n is less than 10")
}

else[edit]

if n < 10 {
    print("n is less than 10")
} else {
    print("n is not less than 10")
}

switch[edit]

switch n {
    case 0:
        print("n is zero")
    case 1:
        print("n is one")
    default:
        print("n is neither one nor zero")
}

Loops[edit]

Loops are used to repeat a segment of code until a condition is met.

for[edit]

for n in 0 ..< 10 {
    print(n)
}

while[edit]

while n < 10 {
    n += 1
}

repeat while[edit]

repeat {
    n += 1
} while n < 10