swift class与struct区别

class是通过引用传递,struct是通过值传递。

  把结构体看作是值,把类看作是物体。

    结构体:位置(经纬度)、坐标(二维坐标、三维坐标)、温度等等可以直接用值来表示的数据。

    类:人、车、动物等。

class可以继承,struct不可以继承。

struct比class更“轻量级”,struct分配在栈中,class分配在堆中。

class Person {    
    var age = 18
    init() {
    
    }
    init(age: Int) {
        self.age = age
    }
}

let a = Person()
print(a.age)                //18

let b = Person(age: 20)
print(b.age)                //20

let c = b
c.age += 2
print(c.age)                //22
print(b.age)                //22

let d = b
d.age += 2
print(d.age)                //24
print(c.age)                //24
print(b.age)                //24 
struct Boy {
    var age = 18
    init() {
        
    }
    init(age: Int) {
        self.age = age
    }
}

let e = Boy()
print(e.age)                //18

let f = Boy(age: 20)
print(f.age)                //20

var g = f
g.age += 2
print(f.age)                //20
print(g.age)                //22

 

posted @ 2016-12-02 15:41  紫洁  阅读(977)  评论(2编辑  收藏  举报