swift的类与对象讲解

前端之家收集整理的这篇文章主要介绍了swift的类与对象讲解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  • 最简答的类和对象


import UIKit


class Shape{

var numberOfSides=0;

func ReturnDescription() ->String{

return "it has \(numberOfSides) sides";

}

}

class ViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view,typically from a nib.

var MyShape=Shape();

MyShape.numberOfSides=3;

var StringFromClass=MyShape.ReturnDescription();

println("\(StringFromClass)");

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}



}


但是一般都需要有构造器,需要加init方法


import UIKit


class ShapeWithInit{

var numberOfSide:Int;//类的属性

init(numberOfSideGet:Int){//必须得与上面的变量名字不同

numberOfSide=numberOfSideGet;

}

func GetSimpleDesciption(name:String)->String{

return "hello,\(name),it has \(numberOfSide) sides"

}

}

class ViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view,typically from a nib.

var myShape=ShapeWithInit(numberOfSideGet: 3);//必须的加参数,而且前面必须加构造函数的参数名称,不是属性名称

var stringGet=myShape.GetSimpleDesciption("wtt");

println(stringGet);

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}



}


下面在讲下类的继承。下面的代码包括方法的重写,每一步都有特定的意义在,需要仔细看。


import UIKit


class ShapeWithInit{

var numberOfSide:Int;//类的属性

var shapeAdditional:String;//类的属性

init(numberOfSideFromObject:Int){//必须得与上面的变量名字不同,构造对象的时候需要传参进来。但是不一定所有的属性都需要传进来。

numberOfSide=22;//所有的属性必须在这里被初始化,但是不一定用传进来的参数。额,当然不建议这样做

shapeAdditional="this is class ShapeWhithInit";

}

func GetSimpleDesciption(name:String)->String{

return "hello,\(shapeAdditional),it has \(numberOfSide) sides"

}

}

class Squre:ShapeWithInit{

var lengthOfClass:Double;

init(lengthFromSqureObject:Double,number:Int){//子类的构造方法中,参数多了长度

self.lengthOfClass=lengthFromSqureObject;

super.init(numberOfSideFromObject: number);//父类的构造方法

numberOfSide=4;

}

override func GetSimpleDesciption(name: String) -> String {//如果需要重写父l类的方法需要在前面加上override关键字

return "hello,it is from fulei,additional,\(shapeAdditional).it is from zilei,lengthofclass,\(lengthOfClass),numberofside,\(numberOfSide)";

}

}

class ViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view,typically from a nib.

var mySqure=Squre(lengthFromSqureObject:12.5,number:4);

var stringGet=mySqure.GetSimpleDesciption("wtt");

println(stringGet);

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}



}

猜你在找的Swift相关文章