Swift 九:實例方法

1).實例方法

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

let point = MyPoint()

point.setX(newX: 10)

2).方法的參數(shù)名稱

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)

//調(diào)用實例方法(經(jīng)測試,現(xiàn)在版本全局方法也是如次)的時候,默認從第二個參數(shù)起,
參數(shù)的內(nèi)部參數(shù)名稱都同時作為外部參數(shù)名稱,若要不顯示外部參數(shù)名稱,
則可以使用 _

3).結(jié)構(gòu)體中的mutating方法

值類型(結(jié)構(gòu)體或者枚舉)默認方法是不可以修改屬性的,如果想要修改,
需要做特殊處理: 加關(guān)鍵字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).下標(biāo)subscripts腳本語法

所謂的下標(biāo)腳本語法,就是能夠通過 實例[索引值]來訪問實例中數(shù)據(jù)的一種快捷方式

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 { //下標(biāo)腳本語法
        
        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多索引的實現(xiàn)

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

let mul = Mul()

print(mul[3,2])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容