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

What’s the difference be...

Câu trả lời

In Swift, Any and AnyObject are used to represent values of unknown types, but they serve different purposes and have distinct characteristics.

Any

  • Definition: Any is the most general type in Swift and can represent any type, including value types (such as structs and enums) and reference types (such as classes and protocols).
  • Usage: It is used when you need to work with a mix of different types or when the type of a value is not known at compile-time.
  • Example: You can create a heterogeneous array that holds different types of values:
    swift Copy
    let mixedArray: [Any] = ["Hello", 42, 3.14]
    To access the values, you need to cast them back to their original types:
    swift Copy
    if let firstValue = mixedArray[0] as? String {
        print(firstValue) // "Hello"
    }
    if let secondValue = mixedArray[1] as? Int {
        print(secondValue) // 42
    }

AnyObject

  • Definition: AnyObject is a protocol to which all classes implicitly conform. It can only represent reference types (instances of classes).
  • Usage: It is often used when working with Objective-C APIs that use id or NSObject as a generic type. It is also useful when you want to restrict a protocol to be implemented by classes only.
  • Example: You can create an array that holds instances of different classes:
    swift Copy
    let imageView = UIImageView(image: nil)
    let viewController = UIViewController(nibName: nil, bundle: nil)
    let mixedArray: [AnyObject] = [imageView, viewController]
    `...
senior

senior

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

middle

What’s the difference between a protocol and a class in Swift?

middle

Explain the difference between DispatchQueue.main.async and DispatchQueue.main.sync ?

senior

What is the difference between open and public keywords in Swift?

Bình luận

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

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