Swift 九:实例方法

1).实例方法

class MyPoint {
    var x : Double = 10
    
    func  setX(newX newX : Double) {  // 实例方法
        x = newX
    }
}

let point = MyPoint()

point.setX(newX: 10)

2).方法的参数名称

class MyPoint {
    var x : Double = 10
    
    func  setX(newX : Double , newY : Double , _ newZ : Double) { // 实例方法
        x = newX + newY + newZ
    }
}

let point = MyPoint()

point.setX(10, newY: 10, 11)

//调用实例方法(经测试,现在版本全局方法也是如次)的时候,默认从第二个参数起,
参数的内部参数名称都同时作为外部参数名称,若要不显示外部参数名称,
则可以使用 _

3).结构体中的mutating方法

值类型(结构体或者枚举)默认方法是不可以修改属性的,如果想要修改,
需要做特殊处理: 加关键字mutating

struct MyPoint {
   
   var x : Double = 10
   
   mutating func  setX(newX : Double , newY : Double , _ newZ : Double) { // 实例方法
       
       self.x = newX + newY + newZ
   }
}

var point = MyPoint()

point.setX(10, newY: 10, 11)

4).类方法

class PointClass {
   
   static var x = 10
   
   var y = 10
   
   static func pointFunc () {
       
       print("point")
       
       x = 10
       
       // y = 10 y是对象成员属性 类方法不可以访问 只可以访问类成员属性
   }
}

PointClass.pointFunc()

5).下标subscripts脚本语法

所谓的下标脚本语法,就是能够通过 实例[索引值]来访问实例中数据的一种快捷方式

struct Student {
    
    var math = 0.0
    
    var chinese = 0.0
    
    func score(type:NSString) -> Double {
        
        switch type {
            
        case "math":
            return math
            
        case "chinese" :
            return chinese
            
        default :
            return 0
        }
        
    }
    
    subscript (type:NSString) -> Double { //下标脚本语法
        
        get {
            switch type {
                
            case "math":
                return math
                
            case "chinese" :
                return chinese
                
            default :
                return 0
            }
            
        }
        
        set {
            
            switch type {
                
            case "math":
                math = newValue
                
            case "chinese" :
                chinese = newValue
                
            default : break

            }
            
        }
        
    }
}


var xioali = Student(math: 97, chinese: 89)

print(xioali["math"])

print(xioali.score("math"))

xioali["math"] = 19

print(xioali["math"])

6).subscripts多索引的实现

struct Mul {
    
    subscript (a : Int , b : Int) -> Int {
        
        return a * b
    }
}

let mul = Mul()

print(mul[3,2])

你可能感兴趣的:(Swift 九:实例方法)