您的位置:首页 > 移动开发 > Swift

Swift学习- 方法(十一)

2015-09-30 10:38 429 查看
/*方法是某些特定类型相关联的函数

类、结构体、枚举都可以定义实例方法和类型方法

*/
class Counter {
   
var count = 0
   
func incremnet(){
        ++count
    }
   
func incrementBy(amount:Int){
       
count += amount
    }
   
func reset() {
       
count = 0
    }
}
var count =
Counter()

//count为0

count.incremnet()

//count为1

count.incrementBy(5)

//count为6

count.reset()

//count为0

/*self属性

类型的每一个实例都有一个隐含属性self(相当于其他语言的this),self等于实例本身

下例可省略self,

*/
class Counter1 {
   
var count = 0
   
func incremnet(){
        ++self.count
    }
   
func incrementBy(amount:Int){
       
count += amount
    }
   
func reset() {
       
count = 0
    }
}

//如果实例方法的莫个参数名和实例的莫个属性名字一样,需要用self来消除歧义
struct Point {
   
var x = 0.0, y =
0.0
   
func isToTheRightOfX(x:Double) ->
Bool {

//        self.x 是类属性
       
return self.x > x
    }
}
let somePoint =
Point(x: 4.0, y:
5.0)

if somePoint.isToTheRightOfX(1.0)
{

    print("This Point is to the right of the line where x == 1.0")
}

//This Point is to the right of the line where x == 1.0

/* 在实例方法中修改值类型

结构体和枚举都是值类型,一般情况下,值类型的属性不能在实例方法中修改

如果要修改需要加“mutating(变异,改变)”方法。

*/
struct Point1 {
   
var x = 0.0, y =
0.0
   
mutating func moveByX(deltax:Double , deltay:Double) {
       
x += deltax
       
y += deltay
    }
}
var somePoint1 =
Point1(x: 1.0, y:
1.0)
somePoint1.moveByX(2, deltay:
3)

print("The Point is now at (\(somePoint1.x),
\(somePoint1.y))")

//The Point is now at (3.0, 4.0)

//不能在结构体类型常量上调用变异方法,因为常量属性不能改变,即使是想改变的是常量的变量属性也不行

let fixedPoint =
Point1(x: 3.0, y:
3.0)

//下面语句会报错

//fixedPoint.moveByX(2.0, deltay: 3.0)

//在变异方法中可以为self属性赋予全新的实例
struct Point2 {
   
var x = 0.0, y =
0.0
   
mutating func moveByX(deltax:Double, deltay:Double){
       
self = Point2(x:
x + deltax, y: y + deltay)
    }
}
var somePoint2 =
Point2(x: 1.0, y:
1.0)
somePoint2.moveByX(5, deltay:
5)

print("The Point is now at (\(somePoint2.x),
\(somePoint2.y))")

//The Point is now at (6.0, 6.0)

//枚举的变异方法可以把self设置为相同的枚举类型中的不同的成员
enum TriStateSwitch {
   
case Off, Low, High
   
mutating func next() {
       
switch self {
       
case Off:
           
self = Low
       
case Low:
           
self = High
       
case .High:
           
self = Off

        }
    }
}

var light =
TriStateSwitch.Low

light.next()

print(light)
//High

light.next()

print(light)
//Off

/*类型方法

类、结构体和枚举都可以声明类型方法,在func关键字前面加上关键字static

在类型方法的方法体中,self指向这个类型本身,而不是类型的某个实例。

*/
class SomeClass {
   
static func someTypeMethod() {
       
//
    }
}

SomeClass.someTypeMethod()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift 方法 methods