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

前端 未结 10 1053
醉梦人生
醉梦人生 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条回答
  •  -上瘾入骨i
    2020-11-27 10:31

    A practical rule of thumb is that you use private for variables, constants, inner structs and classes that are used only inside the declaration of your class / struct. You use fileprivate for things that are used inside of your extensions within the same file as your class/struct but outside of their defining curly braces (ie. their lexical scope).

        class ViewController: UIViewController {
            @IBOutlet var tableView: UITableView!
            //This is not used outside of class Viewcontroller
            private var titleText = "Demo"
            //This gets used in the extension
            fileprivate var list = [String]()
            override func viewDidLoad() {
                navigationItem.title = titleText
            }
        }
    
        extension ViewController: UITableViewDataSource {
            func numberOfSections(in tableView: UITableView) -> Int {
                return list.count
            }
        }
    

提交回复
热议问题