//Method:类,结构体,枚举中定义的函数叫方法
/*
method第一个参数可以是local的,后面的必须是external(调用的时候必须在前面加上标签),
当然第一个参数也可以自己加上external限制。
如果不想使用external参数,则可以用一个外部参数_,有无external就会变成不同的函数。
默认有external的参数,和加上_作为外部参数的是不同的函数名,发生重载。
在beta5中,参数类型,external参数,函数名来识别重载的,仅返回值和参数名不同不可以。
init构造函数第一个参数也需要外部标签,beta5中,不管是方法还是init,在不写外部参数
的情况下,默认为参数名。init(p:Int),没有显示的外部参数,默认为p
self:和python一样,swift用self来标记自己,不同的是,默认情况下你不需要总是写出self
只有当参数名和成员属性相同时才需要,注意:参数名优先级比成员变量高。
mutating:值类型的类型不可以在方法中修改属性,如果想修改在需要加上mutating
你还可以在mutating的函数中将self赋值为新的实例✨✨
Type Method:即静态方法,类似于Type property,值类型用关键字static,类用关键字class
类的TypeMethod定义用关键字 calss,值类型的type method用关键字static
Type Method可以访问其他的Type Method而不需要加上类型名,但是非Type method就不需要加上类型名。
Type Method同样可以访问 Type property不需要加上类型名。
Type Method中的self是指类本身,而不代表instance */
class Counter
{
var count = 0
func increament(count:Int, addorminus minus:Bool, test:Bool)
{
minus ? self.count++ : self.count-- //注意问号前后必须有空格
println(self.count)
}
//在调用时不想写外部参数,可以在定义时用_
func increament(count:Int, _ minus:Bool, _ test:Bool) //重载发生。
{
println("我是重载的不需要external参数的函数。")
minus ?self.count++:self.count--
println(self.count)
}
}
var c =Counter()
c.increament(1, addorminus:true, test:false)//自己可以主动加external,不加默认为变量名
c.increament(2, true, false)
//Mutating
struct TestStruct
{
var count = 1
mutatingfunc setCount(count:Int)//如果没有mutating,则不能修改成员变量
{
self.count = count
println("Assign a data to stored property,self.count is\(self.count)")
}
mutating func newObj()
{
self = TestStruct(count:5)
println("Assign a instance to self,self.count is\(self.count)")
}
}
var s =TestStruct(count:0)
s.setCount(2)
s.newObj()
//值类型的枚举同样适用
enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
//TypeMethod 由于类目前只支持Computed property的变量定义为Type property,此处以struct为例说明
struct TestTypeMethod
{
static var countTypeProperty = 1
var countNotTypeProperty = 2
func notTypeMethod()//类可以通过成员函数直接修改成员变量,但是结构体不可以
{
TestTypeMethod.countTypeProperty = 3//非TypeMethod想访问TypeProperty,必须加上类型名。
}
static func typeMethod()
{
countTypeProperty = 2//TypeMethod不需要加类名字就可以直接访问。
}
}