swift类和结构体以及枚举

swift中类,结构体,枚举都具有面对对象特征;但是swift中只有类才能继承,结构体和枚举不能

swift语言很重视结构体,swift中的结构体不仅能定义成员变量,还可以定义成员方法,但是结构体不具有继承性,不具备强制类型转换、析构函数、使用引用计数等能力

枚举:

enum WeekDays{

    case Mondy

    case Tesday

    case Wednesday

    funcwrite(){

        print("hehe")

    }

}

var day =WeekDays.Mondy;

day.write();

类的定义:class 类名{定义类的成员}

结构体的定义:struct 结构体名{定义结构体的成员}

类:class Employee{

var no:Int = 30

static var courseCount : Int = 11 // 定义类属性,不能用class

func saveUsedNum(num :NSInteger) -> Void { num}  //实例函数

class func getRandomNum() ->NSInteger{ return 1;} //类函数,class和static都可以但是只可以用一个

}

let emp = Employee()  //类是引用类型,内部的内容可以发生改变所以一般设为let

print(Employee.courseCount) //输出11

print(Employee.getRandomNum()) //输出1

print(emp.no) //输出30

print(emp.saveUsedNum(num: 10)) //输出10

结构体:struct Department{

var no:Int = 0

var name: String = ""

}

var dept = Department()  

构造和析构:

构造函数:

class Rectangle{

    var width:Double=0.0

    var height:Double=0.0

}

var rect =Rectangle() //这样调用使用了系统自动生成的默认构造函数

相当于:

class Rectangle{

    var width:Double=0.0

    var height:Double=0.0

    int(){

    }

}

而结构体的默认构造函数和类的构造函数不同,下面看结构体的例子:

struct Rectangle{

    var width:Double=0.0

    var height:Double=0.0

}

var rect =Rectangle(width:0.2,height:0.3);这儿与类不同,因为这个类的声明相当于如下代码:

struct Rectangle{

    var width:Double=0.0

    var height:Double=0.0

    init(){}

    init(width:Double,height:Double){self.width=width

        self.height = height

   }

}

析构函数:deinit{

}

你可能感兴趣的:(swift类和结构体以及枚举)