Use of getting and setters in Swift

Source: Internet
Author: User



The following is a brief introduction to how getting and setting in Swift are used:



Xcode version:6.1



The code is first attached:


class Test {
    var num1: Double = 0.0
    init(){
    }
    init(num2: Double){
        self.num1 = num2
    }
    
    var perimeter: Double {
        get {
            return self.num1
        }
        set (newVal){
            self.num1 = newVal
        }
    }
}
var doubleValue = Test(num2: 9.0)
doubleValue
doubleValue.perimeter = 3.0
doubleValue


1. Define a property of the NUM1 variable that is used to detect the access value of the Get,set method.



2. Next define two initialization methods, first parameterless, second generation parameter, initialize the NUM1 variable (also can not need, custom notation).



3. Build Get SE T method: Perimeter I understand that as a class of methods that wrap get and set, the external call to the perimeter method in the test class, the perimeter will automatically determine whether the value is passed or value, to call the corresponding get or set method, to the property read and write.



The A.get method is well understood, and if the Get method is called, the method directly return the corresponding property value.



As with the B.set method, if the set method is called, the method automatically assigns the new value (newval) to the property (NUM1) to modify the property value.






Use of getting and setters in Swift


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.