What is a good example to differentiate between fileprivate and private in Swift3

前端 未结 10 1119
醉梦人生
醉梦人生 2020-11-27 10:03

This article has been helpful in understanding the new access specifiers in Swift 3. It also gives some examples of different usages of fileprivate

10条回答
  •  星月不相逢
    2020-11-27 10:21

    In Swift 4.0, Private is now accessible in extension but within same file. If you declare/define extension in other file, then your private variable will not be accessible to your extension**

    File Private
    File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
    Syntax: fileprivate
    Example: fileprivate class SomeFilePrivateClass {}


    Private
    Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
    Syntax: private
    Example: private class SomePrivateClass {}


    Here is more detail about all access levels: Swift - Access Levels

    Look at this images:
    File: ViewController.swift
    Here extension and view controller both are in same file, hence private variable testPrivateAccessLevel is accessible in extension

    enter image description here


    File: TestFile.swift
    Here extension and view controller both are in different files, hence private variable testPrivateAccessLevel is not accessible in extension.

    enter image description here

    enter image description here


    Here class ViewController2 is a subclass of ViewController and both are in same file. Here private variable testPrivateAccessLevel is not accessible in Subclass but fileprivate is accessible in subclass.

    enter image description here

提交回复
热议问题