main.swift//classdemo-06//import foundationprintln ("Hello, world!") Class definition person Name class person{//define a field age var age:int = 0; Define a field name//? Indicates that name is null nil or not set name is optional var name:string?; Construction Method Init () {//without the number of references age = 5; Name = "Baidu"; Create an object with an initial value}//This construction method takes two parameters of name, age init (name:string,age:int) {self.age =; Self.name = name; [Self xxxx];//xxxx (); } deinit{//destructor Dealloc own active call} func getage ()->int {return age; }//member Method instance method func GetName ()->string{//! can return nil return name!; }//The class method and an object do not have a relationship starting with class is the method classes Func MaxAge ()->int {return 200; }//Ability to create object class func person ()->person{return person () }}func TestClass () {//Declares an object var xiaoming = person (); Xiaoming.age = 100; The Swift field is public//println ("Xiaoming \ (xiaoming.age)"); println ("Xiaoming \ (xiaoming. Getage ()) and name is \ (xiaoming.name) "); var maxAge = Person.maxage (); println ("Max Age is\ (MaxAge)"); var Xiaoli = Person.person (); Xiaoli.name = "Xiao Li"; println ("name is \ (xiaoli.name)"); Constructor two tags must write//normal function First label No Thanks, # The second one must write var Xiaowang = person (name: "Xiao Wang", age:18); println ("Xiaowang is\ (xiaowang.name) age is \ (xiaowang.age)");} TestClass ();
Definition and use of Swift-class