- 最简答的类和对象
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.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。