zoukankan      html  css  js  c++  java
  • Swift语言精要

    1. Stored Property

    eg:

    var number: Int = 0

    2. Computed Property

    eg:

    var area : Double {
      get {
        return width * height
      }

         ...

    }

    完整代码如下:

    class Rectangle {
        var  Double = 0.0
        var height: Double = 0.0
        var area : Double {
            // computed getter
            get {
                return width * height
            }
            // computed setter
            set {
                // Assume equal dimensions (i.e., a square)
                width = sqrt(newValue)
                height = sqrt(newValue)
            }
        }
    }

    测试代码:

    var rect = Rectangle()
    rect.width = 3.0
    rect.height = 4.5
    rect.area // = 13.5
    rect.area = 9 // width & height now both 3.0

    3. Property Observer(属性观察者)

    class PropertyObserverExample {
        var number : Int = 0 {
            willSet(newNumber) {
                println("About to change to (newNumber)")
            }
            didSet(oldNumber) {
                println("Just changed from (oldNumber) to (self.number)!")
            }
        }
    }

    测试代码如下:

    var observer = PropertyObserverExample()
    observer.number = 4
    // prints "About to change to 4", then "Just changed from 0 to 4!"

    4. Lazy Property(属性迟绑定)

    class SomeExpensiveClass {
        init(id : Int) {
            println("Expensive class (id) created!")
        }
    }
    
    class LazyPropertyExample {
        var expensiveClass1 = SomeExpensiveClass(id: 1)
        lazy var expensiveClass2 = SomeExpensiveClass(id: 2)    
        init() {
            println("First class created!")
        }
    }

    测试代码如下:

    var lazyExample = LazyPropertyExample()
    // prints "Expensive class 1 created", then "First class created!"
    lazyExample.expensiveClass1 // prints nothing, it's already created
    lazyExample.expensiveClass2 // prints "Expensive class 2 created!"
  • 相关阅读:
    (文章转载)GetTextMetrics与GetTextExtent的区别
    (文章转载)
    (文章转载)在刷新窗口时经常要调用重绘函数
    (文章转载)MCI编程
    Visual C#的Excel编程
    EXCEL中合并单元格
    Excel、Exchange 和 C# (摘要)
    C# 查询一个值方法ExecuteScalar()
    如何用C#在Excel中生成图表?
    javascript 常用方法
  • 原文地址:https://www.cnblogs.com/davidgu/p/5346042.html
Copyright © 2011-2022 走看看