Computed read-only property vs function in Swift

后端 未结 10 931
忘了有多久
忘了有多久 2020-12-04 11:00

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

class Vehicle {
    var numberOfWheels = 0
    var          


        
10条回答
  •  盖世英雄少女心
    2020-12-04 11:11

    There are situations where you would prefer computed property over normal functions. Such as: returning the full name of an person. You already know the first name and the last name. So really the fullName property is a property not a function. In this case, it is computed property (because you can't set the full name, you can just extract it using the firstname and the lastname)

    class Person{
        let firstName: String
        let lastName: String
        init(firstName: String, lastName: String){
            self.firstName = firstName
            self.lastName = lastName
        }
        var fullName :String{
            return firstName+" "+lastName
        }
    }
    let william = Person(firstName: "William", lastName: "Kinaan")
    william.fullName //William Kinaan
    

提交回复
热议问题