iOS二次发育(swift)类
类的初探
class Person{ var firstName: String var lastName: String init(firstName:String, lastName:String) { self.firstName = firstName self.lastName = lastName } func out() -> String { return self.firstName + self.lastName } func goEast() { self.firstName += "aaa" } } let person = Person(firstName: "1", lastName: "2") person.out() person.firstName = "3"; let person2 = person person2.goEast() person2.out() person === person2/*引用同一块地址*/ struct Location{ var x = 0.0 var y = 0.0 func out() -> Float { return Float(x + y); } } //值类型 方法改变自身,需声明关键字mutating //结构体 struct Location2{ var x = 0 var y = 0 mutating func goEast() { self.x += 1 } } //枚举 enum Switch{ case On case Off mutating func click() { switch self { case .On: self = .Off case .Off: self = .On } } } var button = Switch.Off button.click()
//方法 struct Point{ var x:Float = 0 var y:Float = 0 } struct Size{ var width:Float = 0 var height:Float = 0 } class Rectangle{ var point:Point var size:Size init(point:Point, size:Size) { self.point = point self.size = size } //计算型属性 var center:Point{ get{ let x = self.point.x + self.size.width/2.0 let y = self.point.y + self.size.height/2.0 let point = Point(x: x, y: y) return point }set{ let x = newValue.x - self.size.width/2.0 let y = newValue.y - self.size.height/2.0 self.point = Point(x: x, y: y) } } } let rectangle = Rectangle(point: Point(x:10, y:20), size: Size(width: 20, height: 20)) rectangle.center rectangle.center = Point(x: 1, y: 1) rectangle.point CGRect(x: 0, y: 0, width: 1, height: 1) Int.max Int.min //类方法 struct Matrix { var m: [[Int]] var row: Int var col: Int init? ( _ arr2d: [[Int]] ) { guard arr2d.count > 0 else { return nil } let row = arr2d.count let col = arr2d[0].count for i in 1..<row { if arr2d[i].count != col{ return nil } } self.m = arr2d self.row = row self.col = col } func printMatrix() { for i in 0..<self.row { for j in 0..<self.col { print(self.m[i][j], terminator: "\t") } print() } } static func identityMatrix(n: Int) -> Matrix? { if n <= 0 { return nil } var arr2d: [[Int]] = [] for i in 0..<n { var row = [Int](repeating: 0, count: n) row[i] = 1 arr2d.append(row) } return Matrix(arr2d) } } if let m = Matrix([[1, 2], [3,4]]) { m.printMatrix() } if let m2 = Matrix .identityMatrix(n: 4) { m2.printMatrix() } //property observer 属性观察器 class LightBulb { static let maxCurrent = 30 var current = 0 { // willSet{ // print(newValue) // } didSet { if self.current >= LightBulb.maxCurrent { print("错误\(oldValue)") } } } } let lightBulb = LightBulb() lightBulb.current = 10 lightBulb.current = 40
类的继承
//类方法用static关键字,无法继承,所以要用class关键字 class Math{ class func abs(number: Int) -> Int { if number < 0 { return (-number) } else { return number } } } Math.abs(number: -35) class SubMatn: Math { override class func abs(number: Int) -> Int { return super.abs(number: number) } }