How to create a read-only internally writable property in the Swift class

Source: Internet
Author: User
Tags class definition

Very simple with the private modifier, followed by the Limit keyword set:

class Day{    privatevar0    func showRawValue(){        print("raw is \(rawValue)")    }    func forwardRawValue(){        1    }}

However, if the above class definition is in playground, you will actually find that if you remove the following (set) you can access it externally:

let day = Day()day.rawValue+=1//that‘s OK!day.forwardRawValue()day.showRawValue()

This is because the private modifier in Swift does not have the same meaning as in traditional object-oriented objects, and in swift, private only restricts visibility in the same file. So to think that it really works, you have to be able to understand it in an external file:

class ViewController: UIViewController {    func test(){        let day = Day()        //day.rawValue = 99 Error!!!        day.showRawValue()        day.forwardRawValue()        day.showRawValue()    }}

That ' s ok!;]

How to create a read-only internally writable property in the Swift class

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.