笔记5:Properties

2016-07-20  本文已影响13人  LukeHua

在设计模型的时候,经常要设置存值的问题,因为自学的iOS,心中一直存有疑惑,怎样的写法才是正规专业,怎么样的写法是符合swift语言设计的?记录这篇文章的目的也是让自己好好思考一下这个问题

常见的几种定义变量的写法

简单的定义一个变量,并且给予一个初始值,这样的代码量非常小

 var searchRegionID = "2000"

使用get set方法,定义一个变成,这样的写法安全很多

//1
  private var _shouldSearch:Bool = false
    var shouldSearch:Bool{
        get {
            return _shouldSearch
        }
        set{
            _shouldSearch = newValue
        }
    }

//2 只有get为只读属性,当然很安全啦
    private var shouldSear:Bool = false
    var shouldSearch:Bool{
        get {
            return shouldSear
        }
    }
    //2.1 如果只有get可以简写
    var shouldSearch:Bool{
            return shouldSear
    }


    func setShouldSearch(newShouldSearch:Bool){
        self.shouldSear = newShouldSearch
    }


我们经常还需要定义一些常量(全局变量),我把他们放在一个constant.swift文件内,查了一下,apple的文档中指出

Global variables are variables that are defined outside of any function, method, closure, or type context.Global constants and variables are always computed lazily

一篇Stack overflow回复中指出, 因为直接定义全局变量bug很多,用struct封装一下更安全

struct MyVariables { static var yourVariable = "someString"}

这样使用它,非常方便

let string = MyVariables.yourVariable
print("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"

很多初学者跟我一样,iOS用了很久,但在一些Model设计时不知道用Struct还是Class,借这个节会好好了解一下相关知识,
先上苹果的文档

Classes have additional capabilities that structures do not:

1. Inheritance enables one class to inherit the characteristics of another. 
2. Type casting enables you to check and interpret the type of a class instance at runtime. -
3. Deinitializers enable an instance of a class to free up any resources it has assigned.
4. Reference counting allows more than one reference to a class instance.

简单的说

  1. Class有继承功能,而Struct没有这个功能
  2. 运行时可以做类型转换
  3. 反初始化时Class释放资源
  4. Class通过引用传递,Struct通过值传递

在看别人的文章是,随手做的几点摘要

  1. Array和 Dictionary都是 struct
    2.结构体,枚举以及所有的swift中的基本数据类型,包括Array, Dictionary等,全部都是值传递的。
  2. 我记得之前用的时候,NSMutableArray是引用传递的。(待验证)
  3. 类方法的声明和定义需要在关键字func前添加class关键字
  4. willSet和didSet set和get 是不能共存的.
上一篇 下一篇

猜你喜欢

热点阅读