Preface
When Swift first introduced access levels, there was some confusion and confusion about this. While developers are excited about adding access control to the Swift programming language, the private keyword behaves differently than other programming languages.
In swift 3.0, if the declared variable or method was prefixed with private, it can only be used in the current class and cannot be used in extension. If it is changed to fileprivate, but it can be instantiated in other classes, the scope of the attribute will be larger, and it may accidentally cause abuse of the attribute.
Therefore, in Swift 4, the scope of the private attribute is expanded to the extension and is limited to struct and extension, so there is no need to change it to fileprivate anymore.
What are the new changes in Swift 4.0?
- String type is more user-friendly, with multiple lines of string literals, supports Range, and is also considered a collection type
- Improved access to private access, private access modifier
- Smarter and safer Key Value Coding
- Dictionary and collections
- Archive and serialization
- Single-sided range
- General subscript
- ( __ : _ _ )
- Related Type Limitations
- Classes and protocols exist
- Restrictions @objc comments
The main text of this article is introduced below:
On the code
class ViewController: UIViewController { var test = "" private var test1 = "" fileprivate var test2 = "" override func viewDidLoad() { () testIt() // An error will be reported before and needs to be modified to fileprivate } func testForNormal(){ } private func testForPrivate(){ } fileprivate func testForfileprivate(){ } override func didReceiveMemoryWarning() { () // Dispose of any resources that can be recreated. } } extension ViewController { private func testIt(){ testForPrivate() /// Swift 4.0 can be accessed before not available } } class other { let a = ViewController() func lalal(){ _ = /// Normal _ = a.test2 /// fileprivate () /// Normal () /// fileprivate () /// Error 'testForPrivate' is inaccessible due to 'private' protection level } }
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.