swift--(i) Adding attributes for swift built-in types

Source: Internet
Author: User

When looking at Apple ’s official Swift Language, I encountered an experiment: Write an extension for the Double type that add an absoluteValue property. When adding properties directly using extension, an error occurred (of course, the code has not been written yet, PlayGround It is easy to use).


extension Double {// add absoluteValue property to Double type by using extension.
    var absoluteValue: Double {
    }
}
    The result is an error, saying: ‘var’ declaration without getter / setter method not allowed here

    @Author: Twlkyao reprint or quote please keep this line.

    According to the cause of the error, add getter and setter methods to solve this problem perfectly.


extension Double {// add absoluteValue property to Double type by using extension.
    var absoluteValue: Double {
        get {// the get could be omitted.
            if self> 0 {
                return self
            } else {
                return -self
            }
        }
    }
}

var doubleNum = -2.2
doubleNum.absoluteValue


    Note: extensionkeyword can add calculation attributes (instance attributes or class attributes) to the structure or class, and also enable the structure or class to adopt a specific protocol.

Swift-(1) Add properties to Swift built-in types

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.