struct & class
Both struct and class have:
1. var
var body: some View {
Text("Hellow World!")
}
2. let
let defaultColor = Color.orange
3. functions
func multiply(operand: Int, by: Int) -> Int {
return operand * by
}
multiply(operand: 5, by: 6)
- 注意:每个parameter可以有2个label:
func multiply(_ operand: Int, by otherOperand: Int) -> Int { return operand * otherOperand } multiply(5, by: 6)第一个label给外部输入用;第二个label给func内部用。
_means "unused" / "leave it out".
4. initializers
- Special functions that are called when creating a
structorclass.
struct MemoryGame {
init (numberOfParisOfCards: Int) {
// create a game with that many paris of cards.
}
}
- 一个struct中可以有很多个
init,每个init携带不同参数。
Difference between struct and class
-
structis a Value type, butclassis a Reference type.struct class Value type Reference type copied when passed or assigned passed around via pointersinheapcopy on write automatically reference counted functional programming object-oriented programming no inheritance inheritance (single) "free" init initializes ALL vars "free" init initializes NO vars Mutabilityexplicitly statedAlways mutable - Most things you see are struct. Arrays, Bools, Dictionaries...
-
structis your "go-to" data structure, whereasclassis only used in specific circumstances. - ViewModel in MVVM is always a
class. - UIKit (old-style iOS) is class-based.
protocol
-
Viewis a protocol.
type parameter (don't care)
Sometimes we may want to manipulate data structures that we are "type agnostic" about. In other words, we do not know what type it is and we do not care.
Swift is a strongly-typed language, so we cannot have variables that are "untyped". Therefore, we use
type parameter.An awesome example of generics:
Array.
How Array uses a "don't care" type
struct Array<Element> { ... func append(_ element; Element) {...} }
- The type of the argument to
appendisElement: a "don't care" type.- The
Elementis determined when someone uses Array.var a = Array<Int>() a.append(5)
enum
functions
- Functions are also types.
var operation: (Double) -> Double
This is a var called operation. It is of type "function that takes a Double and returns a Double".
func square(operand: Double) -> Double {
return operand * operand
}
operation = square
let result = operation(4) // result would equal 16
operation = sqrt //sqrt is a built-in function
- We do not use argument labels (e.g.
operand:) when executing function types.
Closures
When passing functions around that we are very often inlining them, we call such an inlined function a closure