Lecture 3

SEUNGHWANLEE·2021년 9월 20일
0

Swift

목록 보기
2/3
post-thumbnail

CS193p Developing Apps for iOS, Standford University 강의 👉

이전에 포스팅했던 BLoC pattern과 상당히 비슷한 개념을 갖고 있습니다. BLoC을 이미 알고 있다면 MVVM 패러다임을 이해하는 데 큰 어려움이 없을 듯 합니다. 🤩

MVVM

Model-View-ViewModel
Swift의 기본이 되는 Design Paradigm이다. Model과 View를 분리해서 사용해야한다.

Model

  • UI와는 독립적이기때문에 import SwiftUI 를 할 필요가 없다
  • 애플리케이션이 어떤 일을 하는 지 Data와 작업
  • 사용자의 선택을 포함하는 Logic이 있다
  • "The Truth", Data와 Logic이 결합되있는 상태

View

  • Model에 Information을 저장하지 않는다
  • Reactive, View 스스로 결정하지 않고 Model를 반영한다
  • Stateless, state는 View에 저장하지 않기 때문이다
  • Declared, var body: some View
  • @immutable
  • 항상 자동으로 수정된 Model과 관련된 View만 변경된다 (only affected View can be changed)
  • View는 항상 ViewModel을 거쳐 Model에게 어떤 상태인지 물어본다 (View always get data asking Model via ViewModel)

ViewModel

  • View를 rebuild하기 위해서 View와 Model의 중간다리 역할 (Binds View to Model, react to rebuild)
  • Interpreter
  • GateKeeper for the Model, Logic을 담당하기 때문에
  • never can be out of sync without Model

Process

사용자 의도(User Intent)

  1. View에서 이벤트 발생(User's Tap, Swipe)
    : View 👉 ViewModel : calls Intent func
  2. ViewModel이 Model을 수정
    : 앞서 호출된 func 이 만들어낸 결과를 토대로 Model을 수정
  3. Model에서 변화를 알아챔
    : ViewModel은 Model의 변화를 알 수 있어 모든 변화를 추척한다 (track all the changes)
  4. View들에게 "something changed"라고 알려준다
    : 알려주면 해당되는 View가 반응한다 (automatically observes publications)
  5. Data를 받아서 새롭게 build한다
    : 해당되는 View들만 pulls Data해서 다시 build

Architecture

Varieties of Types

struct and class things in common

먼저 공통점에 대해서 다루었다.

  • stored vars: stored in memory
  • computed vars: result of evaluating some code
  • constant lets: never change
  • have functions
func multiply(_ operand: Int, by otherOperand: Int) -> Int {
	return operand * otherOperand
}
multiply(5, by: 6)

위와 같이 사용하는 것이 가독성이 더 좋아 Swift에서 지향하는 방식이다.

  • initializers: function called when creating struct or class
    init 함수를 여러 argument를 담아서 사용할 수 있다. 예를 들어서 init(a:Int, b:Int)init(a:Int) 모두 사용할 수 있다.

differences

structclass
TypeValue TypesReferences Type
WorkflowCopy on writeAutomatically reference counted
CharacteristicFunctional ProgrammingObject-oriented Programming
InheritenceXO (only single)
initAll varsNO vars
MutableMust be explicitly statedAlways
Concept"Go to" data structuresspecific circumstances

struct

  • Value Types
    - 전달되거나 할당받을 때 복사로 이루어진다 (Copied when passed or assigned)
  • 메모리를 공유하지 않는다 (Copy on write (not real copy))
  • Functional Programming
  • 상속이 안된다 (No inheritance)
  • init 함수 argument에 여러 var를 선언할 수 있다 ("Free" init initializes All vars)
    - 사용자가 정의한 init 함수가 없다면 어떤 것이든 초기화될 수 있다 (everythings can be initialized(when there's no custom init))
  • 변경될 수 있는 건 모두 명시되어야 한다 (Mutability must be explicitly stated)
    - var vs. let, 이 두개로 모두 표시 가능
  • 불러오듯이 사용, Your "go to" data structures
  • 지금까지 사용된 모든 것은 거의 struct (Everything you've seen so far is a struct)
    - except View which is protocol

class

  • References Type
    - 메모리를 공유한다 (Passed around via pointers(stacked in memory))
  • Swift는 사용되고 있는 Object를 count하고 있어서 사용되는 것이 없다면 메모리에서 자동으로 지운다 (Automatically reference counted (better than garbage collection))
  • Object-oriented Programmming
  • Inheritance (single)
  • init 함수 argument에 var를 선언할 수 없다 ("Free" init initializes NO vars)
  • 항상 수정가능, Always mutable
  • ViewModel에서만 사용
    - Used in specific circumstances
    • ViewModel in MVVM is always a class
      - UIKit is also class

protocol

next lecture

"Don't Care" type (a.k.a generics)

다른 언어에서는 Generic으로 불리는 것, 교수님이 Don't Care라고 사용 중

  • 명시될 필요가 없는 것 (Sometimes we just don't care)
  • Compiler가 직접 확인하도록 하는 것 (make compiler look at out code)
  • ex) Array
    Q. 범용적으로 사용되려면 여러 원소를 담고있는 배열을 어떻게 만들어야할까? 배열은 자기자신의 타입을 어떻게 나타낼까?
    A. < >를 이용해서 나타낸다 var a = Array<Int>()
  • Type Parameter
    - 우리가 상관없다고 일컫는 것은 사실 Type Parameter이다 (what we call "don't care" here)
    • Swift combines this with protocols to take it all to the next level

enum

next lecture

functions

  • argument의 Type과 return Type를 명시
  • Functional Programming, func를 다른 func에게 전달해 사용
  • ex).
    (Int, Int) -> Bool
    (Double) -> Void
    () -> Array<String>
    () -> Void
    모두 Type이다 (Int, Bool, Double, Void, ...)
  • 괄호안에 변수를 넣어 사용하는 방식이 때로는 가독성이 좋기도 하고 굳이 label를 사용하지 않고 사용할때가 좋을 때도 있다
    (calling functions with variable of function, we don't need labels assigned, just use with parentheses)

Functions as Types

  • Closures
    - similar to "inline functions", captures some of states
    • functional programming

static

강의에서는 Global하게 사용하기위해서 static을 사용하였지만 아래 블로그가 자세한 설명이 되어있어 첨부한다.
Effectively using static and class methods and properties - Dony wals 👉

profile
잡동사니 😁

0개의 댓글