-
Notifications
You must be signed in to change notification settings - Fork 8
Swift 2 notes
Notes from Swift: Programming, Master's Handbook.
- Booleans:
TrueorFalse - Integers: Positive and negative whole numbers
- Characters: Single ASCII symbol or letter
- Floats: Decimal numbers.
- Strings: Characters in sequence
- Lists: Mutable sequence of individual elements:
[3, 1, 4, 9, 2],["Apple", "Banana", "Caramel"],[true, false, true, true](values are typically of the same data type) - Enumerations: Immutable sets of data values (values are the same data type)
- Itemizations: Combination of different data types to form a finite set:
[false, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, true]
// <- this is a single-line comment
/*
* <- this is a multi-line comment
*/- Booleans must be lowercase
true, false - Floats need to have
0and a decimal place:0.12(not.12)
-
letdeclares an immutable constant -
vardeclares a mutable variable - Commas not required at end of lines
… are made up of atomic data and/or other composite structures.
These can be classes or structs.
Think of Classes as Blueprints for a house, and Objects as actual houses designed from the Blueprints.
- Classes = more flexible
- Structs = Quicker to load and access
The rule of thumb is: if you want something quick and simple, design a Struct. If you want flexibility, design a Class.
// Class:
class fooClass {
let baz = 1
}
let test1:fooClass = fooClass()
print(test1.baz) // 1
// Struct:
struct fooStruct {
let baz = 2
}
let test2 = fooStruct()
print(test2.baz) // 2… are variables that can be defined but do not require an initial value:
let fark:String?
// ... later:
fark = "hello"In a type declaration the ! is similar to the ?. Both are an optional, but the ! is an “implicitly unwrapped” optional, meaning that you do not have to unwrap it to access the value (but it can still be nil).
– http://stackoverflow.com/a/24122706/922323
Overall, the syntax structure for Swift functions are so:
func functionName(<inputName>:<input DataType>)-><output DataType> {
// Your function’s actions here …
return data // Must match output DataType.
}If your Swift function has no data outputs, simply set its output type to Void.
Use <xxx> to declare the generic object type being passed in:
func typeof<obj>(obj:obj)->String {
return Mirror(reflecting:obj).description
}You could even pass back the same generic object in the ->obj return value.