zoukankan      html  css  js  c++  java
  • Computed read-only property vs function in Swift

    In the Introduction to Swift WWDC session, a read-only property description is demonstrated:

    class Vehicle {
        var numberOfWheels = 0
        var description: String {
            return "(numberOfWheels) wheels"
        }
    }
    
    let vehicle = Vehicle()
    println(vehicle.description)
    

    Are there any implications to choosing the above approach over using a method instead:

    class Vehicle {
        var numberOfWheels = 0
        func description() -> String {
            return "(numberOfWheels) wheels"
        }
    }
    
    let vehicle = Vehicle()
    println(vehicle.description())
    

    It seems to me that the most obvious reasons you would choose a read-only computed property are:

    Semantics - in this example it makes sense for description to be a property of the class, rather than an action it performs.
    Brevity/Clarity - prevents the need to use empty parentheses when getting the value.
    Clearly the above example is overly simple, but are there other good reasons to choose one over the other? For example, are there some features of functions or properties that would guide your decision of which to use?

    N.B. At first glance this seems like quite a common OOP question, but I'm keen to know of any Swift-specific features that would guide best practice when using this language.

  • 相关阅读:
    解决mybatis查询返回结果值串查
    MSSQL Export Excel
    Linux检测硬盘读取速度
    Linux修改用户密码
    Linux系统关闭防火墙端口
    Linux系统查看系统信息
    查找一个String中存储的多个数据
    编辑器vi命令
    去除一段文字最后一个符号
    替换Jar包中的一个文件 Replace a file in a JAR
  • 原文地址:https://www.cnblogs.com/davidyff/p/5383350.html
Copyright © 2011-2022 走看看