您好,登錄后才能下訂單哦!
本篇內容介紹了“如何使用swift類方法”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
//類的實例方法 class Counter { var count = 0 func increment() { count += 1 } func increment(by count: Int) { self.count += count } func reset() { count = 0 } } let counter = Counter() print(counter.count) //0 counter.increment() print(counter.count) //1 counter.increment(by: 10) print(counter.count) //11 counter.reset() print(counter.count) //0
//結構體修改屬性 mutating struct Point { var x = 0.0, y = 0.0 mutating func moveBy(x deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } var point = Point(x: 1.0, y: 1.0) point.moveBy(x: 2.0, y: 2.0) print(point) //Point(x: 3.0, y: 3.0)
//枚舉修改屬性 mutating enum TriStateSwitch { case off, low, high mutating func next() { switch self { case .off: self = .low case .low: self = .high case .high: self = .off } } } var ovenLight = TriStateSwitch.low print(ovenLight) //low ovenLight.next() print(ovenLight) //high ovenLight.next() print(ovenLight) //off
//類方法 class Tool { static func getSize() -> (Int, Int) { return (100, 100) } } print(Tool.getSize()) //(100, 100)
//結構體用下標訪問 subscript struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print(threeTimesTable[4]) //12
//類用下標訪問 subscript class Matrix { let rows: Int, cols: Int var grid: [Double] init(rows: Int, cols: Int) { self.rows = rows self.cols = cols grid = Array(repeating: 0.0, count: rows * cols) } func indexIsValid(row: Int, col: Int) -> Bool { return row >= 0 && row < rows && col >= 0 && col < cols } subscript(row: Int, col: Int) -> Double { get { assert(indexIsValid(row: row, col: col), "Index out of range") return grid[(row * cols) + col] } set { assert(indexIsValid(row: row, col: col), "Index out of range") grid[(row * cols) + col] = newValue } } } var matrix = Matrix(rows: 2, cols: 2) print(matrix.grid) //[0.0, 0.0, 0.0, 0.0] matrix[0, 0] = 1.0 matrix[0, 1] = 2.0 matrix[1, 0] = 3.0 matrix[1, 1] = 4.0 print(matrix.grid) //[1.0, 2.0, 3.0, 4.0]
//枚舉用下標訪問 subscript enum Direction: Int { case top, right, bottom, left static subscript(n: Int) -> Direction { return Direction(rawValue: n)! } } let right = Direction[1] print(right) //right
“如何使用swift類方法”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。