QSD的Swift妙妙屋3:妙妙的理论之6种Type

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 struct or class.
struct MemoryGame {
    init (numberOfParisOfCards: Int) {
        // create a game with that many paris of cards.
    }
}
  • 一个struct中可以有很多个init,每个init携带不同参数。

Difference between struct and class

  • struct is a Value type, but class is a Reference type.
    struct class
    Value type Reference type
    copied when passed or assigned passed around via pointers in heap
    copy on write automatically reference counted
    functional programming object-oriented programming
    no inheritance inheritance (single)
    "free" init initializes ALL vars "free" init initializes NO vars
    Mutability explicitly stated Always mutable
  • Most things you see are struct. Arrays, Bools, Dictionaries...
  • struct is your "go-to" data structure, whereas class is only used in specific circumstances.
  • ViewModel in MVVM is always a class.
  • UIKit (old-style iOS) is class-based.

protocol

  • View is 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 append is Element: a "don't care" type.
  • The Element is 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


SwiftUI is mostly about functional programming, therefore "functions as types" is a very important concept in Swift.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。