您的位置:首页 > 移动开发 > Swift

Swift2.0:数据类型笔记

2016-07-06 17:53 435 查看
Variables、Constant、Data Types:

data types:

Int

Float

Double

Bool

Character

String

UInt

CGFloat

Variables:var

var count: Int
var shouldRemind: Bool var text: String
var list: [ChecklistItem]

Data Type Convert:


var i = 10
var f: Float
f = i // error 
f = Float(i) // OK

Type Annotation:

var i: Double = 10

Complex Types:need instantiating

allocation:(存储一个ChecklistItem对象到item变量里,此时还没创建ChecklistItem对象)

var item: ChecklistItem


initialization:(创建ChecklistItem对象,赋初始值)

item = ChecklistItem()

合并:

Instantiating:

var item = ChecklistItem()


scope:

Local variable/Instance variable

嵌套方法中同名变量,可以用self.variable来代表全局变量。

Constant:let

let pi = 3.141592
let difference = abs(targetValue - currentValue) let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")


*如果常量对一个方法来说是局部变量,每次调用这个方法都可以给这个常量赋予一个新的值。所以声明建议都用let,因为如果错误会有提示。

value type/reference type

Int,String,struct,enum…/objects defined with class

collection object

array:

// an array of ChecklistItem objects:
var items: Array<ChecklistItem> // using shorthand notation:
var items: [ChecklistItem]
// making an instance of the array:
items = [ChecklistItem]()


dictionary:stores key-value pairs

// a dictionary that stores (String, Int) pairs, for example a // list of people’s names and their ages:
var ages: Dictionary<String, Int>

// using shorthand notation:

var ages: [String: Int]
// making an instance of the dictionary:

ages = [String: Int]()

// accessing an object from the dictionary:

var age = dict["Jony Ive"]
*也就是说,数组用Integer标记,词典用String标记。

  Array和dictionary都是泛型——提高代码复用。

optional:declare a variable has no value

var checklistToEdit: Checklist? 

binding or unwrapping:用optional之前要判断它是否有值的过程

if let checklist = checklistToEdit {
// “checklist” now contains the real object

} else {
// the optional was nil

}


不确定:用if let

if let age = dict["Jony Ive"] { // use the value of age

}


确定:用force unwrapping:! means the value won’t be nil

var age = dict["Jony Ive"]!
optional chaining:自判断连接

navigationController?.delegate = self

相当于:

if navigationController != nil { navigationController!.delegate = self }
implicitly unwrapped optional隐式解析类型(不能在定义时给定初始值)

var dataModel: DataModel! 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: