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

When to use fileprivate ...

Câu trả lời

In Swift, the fileprivate access modifier is used to restrict the visibility of an entity to its own defining source file. This means that any code within the same file can access the fileprivate entity, but it is not accessible from other files. Here are some scenarios where you might use fileprivate:

  1. Multiple Types in One File: When you have multiple classes, structs, or extensions within the same file that need to interact with each other but should not be accessible from outside the file. For example, if you have a helper class or struct that is only relevant within the context of the file, you can use fileprivate to ensure it is not exposed outside.

    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
        }
    }
  2. Encapsulation within a File: When you want to encapsulate certain implementation details within a file but still need to share them among different types or extensions within that file. This helps in maintaining a clean and organized codebase by keeping related code together while hiding it from the rest of the project.

  3. Extensions and Subclasses: When you have extensions or subclasses within the same file that need to access certain properties or methods of the main class. Using fileprivate allows these extensions or subclasses to access the necessary members without exposing them to the entire module.

    swift Copy
    class Widget {
        fileprivate func fileprivateMethod() { ... }
    }
    
    class SpecialWidget: Widget {
        func start() {
            // privateMethod() // No access to private method...
senior

senior

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

senior

When is it safe to use an unowned reference?

middle

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

senior

Explain when to use different Swift casting operators?

Bình luận

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

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