Câu hỏi phỏng vấn Swift
Câu hỏi

What is the difference betwe...

Câu trả lời

In Swift, fileprivate and private are both access control modifiers used to restrict access to properties, methods, types, and other code elements. However, they differ in the scope of access they provide.

private

  • Scope: The private access level restricts the use of an entity to the enclosing declaration (such as a class, struct, or enum) and to extensions of that declaration that are in the same file.
  • Usage: Use private when you want to hide an element completely within its enclosing declaration and only allow access through its public interface. This promotes encapsulation and improves code maintainability.
  • Example:
    swift Copy
    class SomeClass {
        private var somePrivateVariable = 0
    
        private func somePrivateMethod() {
            // This method can only be accessed within SomeClass
        }
    }
    
    extension SomeClass {
        func anotherMethod() {
            somePrivateMethod() // Accessible because it's in the same file and part of the same type
        }
    }

fileprivate

  • Scope: The fileprivate access level restricts the use of an entity to its own defining source file. This means that any code within the same file can access the fileprivate entity, regardless of whether it is within the same type or not.
  • Usage: Use fileprivate when you have helper methods or properties that are useful within the same file but don’t need to be exposed publicly. This can help reduce code duplication and improve organization within a single file.
  • Example:
    swift Copy
    final class ImageViewController: UIViewController {
        fileprivate var imageView: UIImageView!
    }
    
    struct ImageProvider {
        let newImage: UIImage
    
        func updateImage(in viewController: ImageViewController) {
            // As we used fileprivate, we can now access the imageView property.
            viewController.imageView.image = newImage
        }
    }

Key Differences

  • Visibility: private is more restrictive than fileprivate. A `p...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

When would you use self in a method?

middle

What Classes and Structs have in common in Swift and what are their differences?

senior

What's wrong with this code?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào