Swift学习- 方法(十一)

/*方法是某些特定类型相关联的函数

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

*/

class Counter {

    var count = 0

    func incremnet(){

        ++count

    }

    func incrementBy(amount:Int){

        count += amount

    }

    func reset() {

        count = 0

    }

}

var count = Counter()

//count0

count.incremnet()

//count1

count.incrementBy(5)

//count6

count.reset()

//count0


/*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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值