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.

}



}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...