Swift Programming-Note 05-MVVM

Lecture03:

Mdel-View-ViewModel (MVVM)

        A "coding organizing" architectural design paradigm.

        Must be adhered to for SwiftUI to work.

        It is different from MVC (Model View Controller) that UIKit (old-style iOS) uses.

 

Architecture

  • MVVM

        Design paradigm

  • Varieties of Types

        struct

        class

        protocol

        "Don't care" type (aka generics)

        enum

        functions

 

  • Both struct adn class have ... pretty much exactly the same syntax. 
    • Stored vars (the kind you are used to, ie., stored in memory)
    • computed vars (i.e. those whose value is the result of evaluating some code)
    • constant lets (i.e. vars whose values never change)
    • var body: some View {
      return Text("Hello World")
      }

      functions

    • // 显式输入两个参数operand 和 by
      func multiply(operand: Int, by: Int) -> Int {
          return operand * by
      }
      multiply(operand: 5, by: 6)
      
      //只显式输入一个参数otheroperand,另一个没有提示 默认输入到operand参数
      func multiply(_ operand:Int, by otherOperand: Int) -> Int {
          return operand * otherOperand
      }
      multiply(5, by: 6)

      initializers (i.e. special functions that are called when creating a struct or class)

    • struct RoundedRectangle {
          init( cornerRadius: CGFloat) {
              // initialize this rectangle with that cornerRadius
          }
          init(cornerSize: CGSize) {
              // initialize this rectangle with that cornerSize
          }
      }
      
      
      struct MemoryGame {
          init(numberOfPairsOfCards: Int){
              // create a game with that many pairs of cards
          }
      }

      So what's the difference between struct and class?

struct        class
Value type  Reference type
Copied when passed or assigned Passed around via pointers
Copy on writeAutomatically reference counted
Functional programmingObject-oriented programming
"Free" init initializes ALL vars"Free" init initializes NO vars
Mutability must be explicitly statedAlways mutable
Your "go to" data structureUsed in specific circumstances
Everything you're seen so far is a struct(except View which is a protocol)The ViewModel in MVVM is always a class (also, UIKit (old style iOS) is class-based

Generics

  •         Sometimes we just don't care

We may want to manipulate data structures that we are "type agnostic" about.

In other words, we don't know what type something is and we don't care.

But Swift is a strongly-typed language, so we don't use variables and such that are "untyped".

So how do we specify the type of soemthing when we don't vare what type it is?

We use a "don't care" type (we calll this feature "genetics")--范型

How Array uses a "don't care" type

Array's declearation looks something like this ...

struct Array<Element> {
    ...
    func append(_ element: Element){ ... }
}
    

The type of the argument to append is Element. A "don't care: type.

Array's implementation of append knows nothing about that argument and it does not care.

Element is not any known struct or class or protocal, it's just a placeholder for a type.

The code for using an Array looks something like this...

var a = Array<Int>()
a.append(5)
a.append(22)

When someone uses Array, that's when Element gets determined(by Array<Int>)

Note that Array has to let the world know the names of all of its "don't care" types in its API.

It does this with the < > notation on its struct declaration Array<Element> above.

That's how users of Array know that they have to say what type Element actually is.

var a = Array<Int>()

It is perfectly legal to have multiple "don't care" types in the above (e.g. <Element, foo>)

  • Type Parameter

I willl often refer to these types like element in Array as a "don't care" type

If you ask Array what type its elements are, it will say "I don't care".

But its actual name is Type Parameter.

Other languages most of you may know (e.g. Java) hava a similar feature.

However, Swift combines this with protocols to take it all to  the next level.

We'll talk about that next week!

Functions as Types

  • Functions are people* too! ( * er, types)

You can declare a variable (or parameter to a func or whatever) to be of type "function".

The syntax for this includes the types of the arguments and return value.

You can do this anywhere any other type is allowed.

Examples ...

(Int, Int)   -> Bool     // takes two Ints and returns a Bool
(Double)     -> Void     // takes a Double and returns nothing
() -> Array<String>      // takes no arguments and returns an Array of Strings
() -> Void               // takes no arguments and returns nothing (this is a common one)

All off the above a just types. No different than Bool or View or Array<Int>. All are types

var foo: (Double) -> Void //foo's type: "function that takes a Double, returns nothing"
func doSomething(what: () -> Bool) // what's type: "function, takes nothing, returns Bool"

Example ...

var operation: (Double) -> Double
// This is a var called operation.
// It is of type"function that takes a Double and returns a Double".

// Here a simple function that takes a Double and return a Double ...
func square(operand: Double) -> Double {
    return operand * operand
}

operation = square //just assigning a value to the operation var, nothing more
let result1 = operand(4) // result1 would equal 16
// Note that we don't use argument labels (e.g. operand:) when executing function types.
operation = sqrt // sqrt is a built-in function which happens to take and return a Double
let retult2 = operation(4) // result2 would be 2
// We'll soon see an example of using a function type for a parameter to a function in our demo

Closures 闭包

It's so common to pass functions around that we are very often "inlining" them.

We call such an inlined function a "closure" and there's special language support for it.

We'll cover this in the demo and again later in the quarter.

Remember that we are mostly doing "functional programming" in SwiftUI.

As the very name implies, "funcitons as types" is a very important concept in Swift. Very.

Architecture

  • MVVM

        Design paradigm

  • Varieties of Types

        struct

        class

        protocol

        "Don't care" type (aka generics)

        enum

        functions

  • MVVM and Types in Action

Now that we know about MVVM, let's implement it in our Memorize application

In doing so, we'll see a lot of what we just talked about ...

We're going to use the special init function (in both our Model and our ViewModel)

We're going to use generics in our implementation of our Model

We're going to use a function as a type in our Model

We're going to see a class for the first time(our ViewModel will be a class)

We're going to implement an "Intent" in our MVVM

And finally, we will make our UI"reactive" through our MVVM design

Whew! Let's get started ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Qt MVVM(Model-View-ViewModel)是一种基于Qt框架的设计模式,用于构建用户界面(UI)和业务逻辑的解耦合的应用程序。它是基于传统的MVC(Model-View-Controller)模式的进一步演化。 在Qt MVVM中,Model负责数据的管理和操作,它提供了底层数据对象和数据操作的接口。View是用户界面的呈现,它通过绑定机制和ViewModel交互,以显示数据和响应用户的操作。ViewModel是连接Model和View的桥梁,它将Model的数据转化为View所需的格式,并将用户的输入和操作转化为Model所需的格式。ViewModel还提供了数据绑定机制,以确保Model和View之间的同步。 通过使用Qt MVVM,我们可以实现以下优点: 1. 解耦合:通过将业务逻辑与用户界面解耦合,使得代码易于维护和测试。ViewModel充当了Model和View之间的中间层,使得它们可以独立地进行修改和调整。 2. 可维护性:由于代码的解耦合,使得我们可以更容易地对应用程序进行修改和更新。当需要改变用户界面或业务逻辑时,只需要修改ViewModel或Model的代码,而不会影响其他部分。 3. 可测试性:MVVM模式提供了更好的测试性,我们可以更容易地编写单元测试,以验证Model和ViewModel的功能是否正常工作。这使得我们可以更好地管理和保证代码的质量。 4. 数据绑定:Qt MVVM提供了高效的数据绑定机制,使得我们可以非常简便地将数据与用户界面关联起来。这大大减少了手动更新UI的工作量,提高了开发效率。 总之,Qt MVVM是一种强大的设计模式,可以帮助我们构建易于维护和测试的应用程序。通过解耦合和数据绑定,它提供了一种更合理和高效的方法来管理用户界面和业务逻辑之间的交互。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊猫鹏-梓潼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值