Fundamentals
Values, variables, and control flow. Sure has four basic types, two kinds of variable, and one opinion about ambiguity.
Variables
let makes an immutable binding; var makes a
mutable one. Types are inferred from the value, or declared if you
prefer. Statements end at the end of the line — no semicolons required,
though they are accepted without comment.
func main() -> Int {
let answer = 42 // Int, forever 42
var count: Int = 0 // Int, changeable
count = count + answer
print(count)
return 0
}
Assigning to a let is an error, and the message tells you
the fix: 'x' is a let; use var if it needs to change. A name
can be declared once per function; shadowing is not a feature Sure
offers, on the grounds that one name should mean one thing.
The basic types
| Type | What it is | Literals |
|---|---|---|
| Int | 64-bit signed integer | 42, -7 |
| Float | 64-bit float | 2.5, 1.5e3, 2e-2 |
| Bool | true or false | true, false |
| String | heap-allocated bytes | "sure", "line\n" |
Arithmetic never mixes types. 1 + 2.0 is an error, not a
conversion; Sure will not guess which precision you meant. Convert
explicitly with to_float(n), and come back down with
trunc, round, floor, or
ceil. % works on Int only.
func main() -> Int {
let ratio = to_float(7) / 2.0 // 3.5
print(round(ratio)) // 4
print(7 % 2) // 1
return 0
}
Choosing
if takes a Bool — not an integer, not a
hopeful expression. Chain with else if.
func describe(n: Int) -> String {
if n < 0 {
return "negative"
} else if n == 0 {
return "zero"
} else {
return "positive"
}
}
func main() -> Int {
print(describe(-3))
return 0
}
When a choice produces a value, use an if expression. The
else is mandatory — an expression must always be worth
something:
func main() -> Int {
let n = 12
let label = if n % 2 == 0 { "even" } else { "odd" }
print(label)
return 0
}
Repeating
while loops on a condition. for iterates a
range (end exclusive), an array, or — as you will see in chapter 9 — a
channel. break and continue do what they say.
func main() -> Int {
var total = 0
for i in 1..11 {
if i % 3 == 0 {
continue
}
total = total + i
}
print(total) // 1..10, skipping multiples of 3: 37
return 0
}
Printing
print(x) takes an Int, Float,
Bool, or String and adds a newline. To build a
line out of mixed pieces, convert with str(x) and
concatenate with +:
func main() -> Int {
let sides = 6
print("a die has " + str(sides) + " sides")
return 0
}