美文网首页
Swift-属性和方法

Swift-属性和方法

作者: qtoq126 | 来源:发表于2018-01-16 15:54 被阅读0次
  1. 计算型属性
struct Point {
    
    var x = 0.0
    var y = 0.0
}

struct Size {
    
    var width = 0.0
    var height = 0.0
}

class Rectangle {
    
    var origin = Point()
    var size = Size()

    //计算型属性必须声明为var
    var center: Point {
        
        // getter和setter方法
        get {
            let centerX = origin.x + size.width / 2
            let centerY = origin.y + size.height / 2
            return Point(x: centerX, y: centerY)
        }
        
        set {
            origin.x = newValue.x - size.width / 2
            origin.y = newValue.y - size.height / 2
        }
    }
    
    init(origin: Point, size: Size) {
        self.origin = origin
        self.size = size
    }
    
    //如果只是取值,直接return即可
    var area: Double {
        return size.height * size.width
    }
}

var rec = Rectangle(origin: Point(), size: Size(width: 10, height: 10))

//使用get方法获取属性值
rec.center
//使用set方法修改center坐标
rec.center = Point()
  1. 类型属性(全局属性)
lass Player {
    
    var name: String
    var totalScore = 0
    
    //全局变量,针对所有对象
    static var highestScore = 0
    
    init(name: String) {
        self.name = name
    }
    
    func play() {
        
        let score = Int(arc4random() % 100)
        print("\(name) played and got \(score) scores")
        
        totalScore += score
        
        if totalScore > Player.highestScore {
            Player.highestScore = totalScore
        }
        print("The total score is \(totalScore)")
        
        print("The highest score is \(Player.highestScore)")
        
    }
}

var player1 = Player(name: "player1")
player1.play()
player1.play()

var player2 = Player(name: "player2")
player2.play()
player2.play()

  1. 类型方法(全局方法)
struct Matrix {

    var m: [[Int]]
    var row: Int
    var col: Int

    init?(arr2d: [[Int]]) {

        guard arr2d.count > 0 else {
            return nil
        }

        let row = arr2d[0].count
        let col = arr2d.count
        
        for i in 1 ..< col {
            if arr2d[i].count != row {
                return nil
            }
            
        }
        
        self.m = arr2d
        self.row = row
        self.col = col
    }
    
    func printMatrix(){
        
        for i in 0 ..< col {
            for j in 0 ..< row {
                print(m[i][j], terminator: " ")
            }
            print()
        }
    }
    
    //通过类型方法创建多阶的单位矩阵模版
      static func identityMatrix(n: Int) -> Matrix? {
        
        if n <= 0 {
            return nil
        }
        
        var arr: [[Int]] = []
        for i in 0 ..< n {
            var row = [Int](repeatElement(0, count: n))
            row[i] = 1
            arr.append(row)
        }
        
        return Matrix(arr2d: arr)
    }

}

if let arr2d = Matrix(arr2d: [[2,3], [4,5], [3, 4]]) {
    arr2d.printMatrix()
}

if let arr = Matrix.identityMatrix(n: 3) {
    arr.printMatrix()
}

  1. 属性观察器
class LightBulb {
    
    static let maxCurrent = 30
    var current = 0 {
        
        //didSet关键字,还有willSet关键字
        didSet {
        
            if current == LightBulb.maxCurrent {
                print("Pay attetion! the current value get to the maxium point")
            }
            else if current > LightBulb.maxCurrent {
                print("The temp is too high!")
                current = oldValue
                print("The current is \(current)")
            }
        }
    }
}

let bulb = LightBulb()

bulb.current = 20
bulb.current = 30
bulb.current = 80
//Pay attetion! the current value get to the maxium point
//The temp is too high!
//The current is 30

//另一个例子
enum Theme {
    
    case DayMode
    case NightMode
}

class UI {
    
    var fontColor: UIColor!
    var backgroundColor: UIColor!
    var themeMode: Theme {
        
        didSet {
            changeTheme(themeMode: themeMode)
//            switch themeMode {
//            case .DayMode:
//                fontColor = UIColor.red
//                backgroundColor = UIColor.red
//            case .NightMode:
//                fontColor = UIColor.black
//                backgroundColor = UIColor.black
//            }
        }
    }
    
    init(themeMode: Theme) {
        self.themeMode = themeMode
        changeTheme(themeMode: themeMode)
//        switch themeMode {
//        case .DayMode:
//            fontColor = UIColor.red
//            backgroundColor = UIColor.red
//        case .NightMode:
//            fontColor = UIColor.black
//            backgroundColor = UIColor.black
//        }
    }
    
    func changeTheme(themeMode: Theme) {
        switch themeMode {
        case .DayMode:
            fontColor = UIColor.red
            backgroundColor = UIColor.red
        case .NightMode:
            fontColor = UIColor.black
            backgroundColor = UIColor.black
        }
    }
}

let ui = UI(themeMode: .DayMode)
ui.backgroundColor
ui.fontColor
ui.themeMode = .NightMode //该属性被赋值时才会开始调用didset方法体
ui.backgroundColor
ui.fontColor

相关文章

  • Swift-属性和方法

    计算型属性 类型属性(全局属性) 类型方法(全局方法) 属性观察器

  • swift-类属性

    了解属性之前,需要先了解前面的swift-类结构内容 - swift-类结构源码探寻[https://www.ji...

  • Swift属性观察方法willSet和didSet

    Swift-属性观察着(willSet和didSet) 属性观察者,类似于触发器.用来监视属性的除了初始化之外的属...

  • 浅谈swift中的属性观察者

    Swift-属性观察者(willSet和didSet) 属性观察者,类似于触发器.用来监视属性的除了初始化之外的属...

  • swift-属性&方法

    计算性属性:自身值的改变需要计算的,可以使用计算性属性定义 属性观察器 懒加载属性

  • Swift-属性

    存储属性 在其最简单的形式中,存储属性是作为特定类或结构的实例的一部分存储的常量或变量。 存储的属性可以是变量存储...

  • Swift-属性

    属性 存储属性(Stored Property)类似于成员变量这个概念存储在实例的内存中结构体,类可以定义存储属性...

  • Swift-类、结构体、属性、方法

    最近项目使用的是OC,后头看之前用Swift开发的一个项目时,发现很多细节都忘记了??。为了回忆和以后方便查看,现...

  • Swift-自定义UITableViewCell和View(XI

    Swift-自定义UITableViewCell和View 概要 本文主要粗略的整理两种方法用于自定义UITabl...

  • 跟着洲洲哥一块学习Swift-属性

    本文首发地址 Swift-属性 首先结构体和枚举都是值类型,类是引用类型。 把结构体赋值给一个变量 * 把结构体...

网友评论

      本文标题:Swift-属性和方法

      本文链接:https://www.haomeiwen.com/subject/nkcsoxtx.html