The Redefining Women Icon Collection

Noun Project launches a new collection of 60+ icons representing women in design, technology and leadership positions, available for free as Public Domain. Visual language has the power to shape…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Swift Interview Questions Latest 2023

1. Difference between Class and Struct

Ans :

1. Value vs. Reference Types: Structs are value types, while classes are reference types. When you create an instance of a struct, it is copied, and any modifications to the copied instance do not affect the original. On the other hand, when you create an instance of a class and assign it to a new variable or constant, both the original and the new variable/reference point to the same instance in memory. Modifying one will affect the other.

2. Inheritance: Classes support inheritance, meaning you can create a subclass that inherits properties and methods from a superclass. Structs, on the other hand, do not support inheritance. They cannot be subclassed or serve as a superclass.

3. Mutability: In Swift, you can define properties and methods as either mutable (changeable) or immutable (constant). With classes, you can choose whether to define properties and methods as mutable or immutable. Structs, however, have an additional behavior — by default, all properties of a struct are immutable (constant) unless the struct instance is explicitly marked as mutable using the mutating keyword. Example : mutating func moveBy(x: Int, y: Int)

4. Memory Management: Classes in Swift use reference counting for memory management. When there are no references to a class instance, it is automatically deallocated from memory. Structs, being value types, do not rely on reference counting and are automatically copied when assigned to a new variable or passed as a function argument.

5. Default Initializers: Classes have an automatically generated default initializer if they don’t define any designated initializers. Structs, on the other hand, always have an automatically generated memberwise initializer that initializes all of their properties.

6. Usage and Preference: Structs are commonly used for small, simple data structures or value-like entities, such as coordinates, colors, or other basic types. Classes are generally used for more complex data structures, model objects, or when you need reference semantics, inheritance, or have more advanced functionality requirements.

2. Which one is faster compare to Class and Struct.

In general, structs are considered to be slightly faster than classes because they are value types. When you create a struct instance, its value is copied whenever it’s assigned to a new variable or passed as an argument to a function.

On the other hand, classes are reference types, meaning that when you assign a class instance to a new variable or pass it as an argument, the reference to the existing instance is used instead of creating a new copy.

3. How many ways we can pass the data between controllers

Ans:

1. Direct accessing controller variables

2. Seques and Propertys

3. Notification

4. CallBackClosers

5. Singleton.Shared models

6. UserDefaluts

7. Dependency injection

8. KVO

4. GCD : Grand Central dispatch

Ans: is a powerful concurrency framework in Swift and iOS/macOS development. Here are the key concepts and components of GCD in Swift:

Dispatch Queues: Dispatch queues are the foundation of GCD. They are responsible for managing the execution of tasks. There are two types of queues:

Serial Queues: Serial queues execute tasks one at a time, in the order they are added. Only one task can execute at a time.

Concurrent Queues: Concurrent queues execute tasks concurrently, allowing multiple tasks to run simultaneously.

Dispatching Tasks: GCD provides different methods to dispatch tasks onto queues:

Global Queues: GCD provides global concurrent queues that are predefined and available for common use cases. They are classified into different quality of service (QoS) classes, indicating the priority and characteristics of the tasks executed on those queues.

Custom Queues: You can create your own serial or concurrent dispatch queues to manage the execution of tasks.

Dispatch Groups: Dispatch groups allow you to monitor the completion of a set of tasks. You can use them to wait for multiple tasks to finish before executing further code.

Barrier Execution: GCD supports barrier execution on concurrent queues. A barrier task is executed with exclusive access to the queue, ensuring that no other tasks are executing concurrently. It can be useful when modifying shared resources to avoid data races.

Dispatch Semaphores: Dispatch semaphores provide a way to control access to a shared resource by limiting the number of concurrent tasks that can access it.

userInteractive: Used for animations, or updating UI.

userInitiated: Used for tasks like loading data from API, preventing the user from making interactions.

utility: Used for tasks that do not need to be tracked by the user.

background: Used for tasks like saving data in the local database or any maintenance code which is not on high priority.

Operation Queue:

Operation Queues provide a convenient way to manage and control the execution of operations in a concurrent and asynchronous manner. They handle dependencies between operations, prioritize the execution order, and can be used to perform various tasks efficiently.

5. What is completion handler

Ans : A completion handler is a closure or callback mechanism commonly used in Swift and other programming languages. It is a way to handle the result or completion of an asynchronous operation or task.

6. How many ways we can store data

Ans: Variables,Constants,Dictinatries,Arrays,Sets,Files(Plist,Json,Text,xml),Coredata

7. Table cell without height constraint

Ans: if you want to dynamically adjust the height of a table view cell based on its content without using a height constraint, you can achieve it by implementing self-sizing cells using Auto Layout and UITableViewAutomaticDimension.

8. KVO

9. Unwoned && Weak

Ans: In summary, unowned references are used when you can guarantee the existence of the referenced object, while weak references are used when the referenced object may be deallocated and you need to handle that possibility. It’s important to consider the object’s lifecycle, potential deallocation scenarios, and the behavior you want to achieve when choosing between unowned and weak references.

Touple: Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value

10 . Application lifecycle

Ans : Not Running, Inactive, Active, Background, Suspend

11 . Difference between Swift and Objective-c

Syntax: One of the most apparent differences is the syntax. Objective-C uses a more verbose syntax with square brackets for method calls and a distinct separation between interface and implementation files. In contrast, Swift has a cleaner and more concise syntax that resembles modern programming languages.

Optional types: Swift introduced the concept of optional types, which allows variables to hold either a value or no value (nil). This helps prevent null pointer errors and promotes safer code. Objective-C does not have native support for optional types.

Automatic Reference Counting (ARC): Swift uses ARC to manage memory automatically, reducing the need for manual memory management. Objective-C, on the other hand, uses manual memory management through retain and release calls.

Interoperability: Swift is fully interoperable with Objective-C, meaning you can use Objective-C code in Swift projects and vice versa. This interoperability allows for a gradual migration from Objective-C to Swift.

Error handling: Swift introduced a robust error handling model using try, catch, and throw statements, making it easier to handle and propagate errors. Objective-C primarily relies on return values or delegate methods for error handling.

Type inference and generics: Swift has strong type inference capabilities, allowing the compiler to infer variable types based on their assigned values. Swift also provides generics, which enable the creation of reusable and type-safe code. Objective-C lacks these features.

Access control: Swift introduced access control modifiers such as public, internal, private, and fileprivate to restrict the visibility and accessibility of code elements. Objective-C uses less strict visibility rules.

Swift Playgrounds: Swift Playgrounds is an interactive coding environment that enables experimentation and learning. It provides an interactive way to experiment with Swift code snippets, visualize output, and learn programming concepts. Objective-C does not have a similar interactive environment.

Open-source: Swift has been open-sourced by Apple, which means it benefits from contributions and enhancements from the community. Objective-C, while widely used, remains proprietary to Apple.

Performance: Swift is generally considered faster than Objective-C, as it was designed with performance optimization in mind. Swift achieves this through various language features and improvements.

12. Explain about Protocol

Ans : In Swift, a protocol defines a blueprint of methods, properties, and other requirements that a class, structure, or enumeration must adopt. It describes a set of rules or capabilities that a type can conform to, enabling interaction and communication between different types in a flexible and decoupled manner.

Protocol Declaration:, Potocol Adoption, Property Requirements:

13. Type Constraints with Protocols: Protocols can be used as type constraints to limit the types that can be used in a generic function or generic type.

Class Protocol: A protocol that can be adopted only by classes.

Protocol Composition: A protocol that combines multiple protocols into a single requirement.

14. Type alias

Ans: Type alias allows you to create an alternative name for an existing type. It can be useful for providing clearer intent, simplifying complex type signatures, or enhancing code readability.

15. Swift Module : A module refers to a single unit of code distribution. It can be a framework, library, or application that is built and packaged as a standalone entity.

A module encapsulates a set of Swift source files and provides a defined interface for other modules to interact with its contents.

Creation,Encapsulated,AccessControllers,Importing modules

16. ViewControllerLifeCycle

Ans: init(nibName:bundle:), loadView(),ViewDidLoad,ViewWillAppear,ViewWilldisappere,Memory Warning:

17. MVC (Model-View-Controller) and MVVM (Model-View-ViewModel) are architectural patterns commonly used in software development.

Responsibilities:

Model: Represents the data and business logic.

View: Displays the user interface and handles user interactions.

Controller: Mediates between the model and the view, handling user input, updating the model, and updating the view.

Communication Flow:

The view forwards user input to the controller.

The controller updates the model based on user input or other events.

The model notifies the controller of any changes.

The controller updates the view based on the model’s changes.

Responsibilities:

Model: Represents the data and business logic.

View: Displays the user interface.

ViewModel: Acts as an intermediary between the model and the view. It contains the presentation logic, exposes data and commands, and communicates with the model.

Communication Flow:

The view binds directly to properties and commands exposed by the ViewModel.

The ViewModel interacts with the model to fetch and manipulate data.

Changes in the ViewModel are automatically reflected in the bound view, and user interactions trigger commands in the ViewModel.

18. Content Hugging priority & Compression Resistance priority.

Ans: Sets the priority with which a view resists being made larger than its intrinsic size. Setting a larger value to this priority indicates that we don’t want the view to grow larger than its content.

Sets the priority with which a view resists being made smaller than its intrinsic size. Setting a higher value means that we don’t want the view to shrink smaller than the intrinsic content size.

19. Access control :

20. SingletoneClass :

21. Using nilcolising, guard let, if let , force unwrapping, optional chaining

22. Touple

Ans: a tuple is a lightweight data structure that allows you to group multiple values into a single compound value. It is a convenient way to combine and pass around related values as a single entity.

Is type safe The type of a tuple is determined by the types of its individual elements.

23. Generics : Generics in Swift enable you to write flexible and reusable code that can work with various types without sacrificing type safety. Generics allow you to define functions, structures, classes, and enums that can operate on a range of different types.

You can define structures, classes, and enums that are parameterized by one or more types.

We can define generics Struct/Classes

24. Stored property and computed property

Stored properties, on the other hand, directly store a value and retain it as part of the instance. They are typically used when you need to store and access values independently.

Computed properties don’t store a value directly. Instead, they calculate and provide a value based on other properties or data. They can have custom getter and setter implementations to perform additional logic when accessing or modifying the property.

// Computed property with getter and setter

Lazy Properties: Lazy properties are properties that are computed only when they are first accessed. They are useful when you want to delay the initialization of a property until it is needed

Property Observers: Property observers allow you to respond to changes in property values. You can define willSet and didSet observers to be notified before or after a property value changes

25. LazyVariable :

A lazy variable is a property that is computed only when it is first accessed, rather than being evaluated immediately. This delayed evaluation can be useful when you have a property that may not be needed right away or requires significant computation.

26 . Objective-c code use in swift and Swift code in objective-c

27. What are higher-order functions and explain about higher-order functions.

Ans : Higher-order functions are functions that can take other functions as parameters or return functions as results.

28 .Higher order functions

Main difference compare to loops

Abstraction Level: Loops require developers to specify the details of iteration and control flow, while higher-order functions abstract away the iteration process and focus on the desired transformation or operation on the data.

Readability and Maintainability: Higher-order functions provide a more expressive and declarative style, making code easier to read, understand, and maintain. The intent of the code is often clearer, reducing the need for manual iteration logic and state management.

Code Reusability: Higher-order functions are designed to be reusable and generic, allowing them to be applied to different data and scenarios. They encapsulate common iteration patterns and operations, reducing code duplication.

Functional Programming Paradigm: Higher-order functions align with functional programming principles by promoting immutability, avoiding side effects, and enabling function composition. They encourage a more functional and declarative coding style.

While both loops and higher-order functions can accomplish similar tasks, higher-order functions provide a more expressive, reusable, and functional approach to data transformation, leading to cleaner and more maintainable code. They help reduce complexity, improve readability, and enable concise expression of algorithms and transformations on collections or sequences of data.

29. Regular Expression

A regular expression, also known as regex, is a sequence of characters that forms a search pattern. It is a powerful tool for pattern matching and manipulating text.

30 . Json Rendering option.

31. TypeInference : Type inference in Swift is a language feature that allows the compiler to automatically determine the data type of a variable or expression based on its initialization or usage context

Variable Initialization:

32. Why we use extensions

Ans : Adding Functionality , Protocol Conformance, Separating Concerns, Code Readability and Clarity:

33. Any and any-object

Ans : Any is a type that represents values of any type, including both value types (such as structs and enums) and reference types (such as classes).

You can use Any when you need to work with values of different types, but you don’t need to know the specific type at compile-time.

AnyObject is a protocol type that represents instances of any class type.

You can use AnyObject when you need to work with objects of different class types but don’t need to know the specific class type at compile-time.

Any can represent values of any type, including both value types and reference types. AnyObject is limited to representing instances of class types only.

Any can hold values of different types at different times. AnyObject can hold instances of different classes but only one class type at a time.

With Any, you may need type casting to work with specific values. With AnyObject, you can directly access methods and properties available on all classes.

Any is a type, while AnyObject is a protocol type.

34 . All Type Of constrains : In Swift, you can apply various types of constraints to generic types using type parameter constraints. These constraints help define requirements or limitations on the generic type.

Type Constraint (: Type):

Generic Parameter Constraint (where clause):

35. Encapsulisation

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) and refers to the practice of hiding the internal implementation details of a class or object and providing a well-defined interface for interacting with it. Encapsulation helps in organizing and structuring code, as well as providing data protection and abstracttion

36. Reference Pointers : In Swift, reference pointers are used to manage reference types, such as classes. A reference pointer is a memory address that points to the location where an object is stored in memory. Instead of directly storing the object itself, reference pointers hold a reference to the object.

37 .Optional chaining & optional binding

Optional Chaining allows you to access properties, methods, and subscripts of an optional value, without explicitly unwrapping the optional.

Example:

38. Optional Any : In Swift, an optional Any is a way to represent a value of any type, including both value types and reference types, with the possibility of being nil. The Any type is a type that can represent an instance of any type at runtime.

39 . App and Bundel ID

App ID:

An App ID is a unique identifier that identifies a specific app or bundle of features within an app.

It is used to register your app with Apple’s developer portal and is required for various app-related tasks, such as provisioning profiles, certificates, and App Store distribution.

An App ID consists of a Team ID and a Bundle ID suffix, separated by a dot (.).

Example: ABCDE12345.com.example.myapp

Bundle ID:

A Bundle ID is a unique identifier for an app or framework within an app bundle. It identifies your app to the operating system and ensures its uniqueness on a particular device.

The Bundle ID is typically set in the app’s Xcode project settings and is embedded in the app’s Info.plist file.

The Bundle ID is used for app-specific operations, such as code signing, app installation, app sandboxing, and identifying app data.

Example: com.example.myapp

40. SSL Pinning

Example :

Implement SSL pinning logic:

In your network request code, retrieve the server’s certificate from the received SSL/TLS handshake response.

Compare the received certificate against the stored trusted certificates or their public key hashes.

If the received certificate matches any of the trusted certificates or public key hashes, consider the connection secure and proceed with the request. Otherwise, reject the connection.

It’s important to ensure that your dynamic configuration update mechanism is secure, properly validated, and protected against tampering to maintain the integrity of SSL pinning within the app. Consult security experts or professionals for guidance on implementing secure dynamic configuration updates in your specific app environment.

41. Retain Cycle:

Retain cycles, also known as memory cycles or strong reference cycles, can occur in Swift when two or more objects hold strong references to each other, creating a situation where they cannot be deallocated by the memory management system. This can lead to memory leaks and unnecessary memory usage. Retain cycles commonly occur when using closures or in relationships between classes or structs with strong reference properties.

42. Nullified

Ans: In Swift, cascading or nullification refers to the process of setting properties of an object to nil or default values in a cascading manner. This is often done to reset or clear the state of an object or to prepare it for reuse.

43. Keychains vs UserDefaults

UserDefaults: UserDefaults stores data as plain text in a property list (plist) file, which is stored in the app’s sandbox. Although the plist file is sandboxed and accessible only to the app, it is not encrypted by default. If an attacker gains access to the device or backups, they can potentially access and extract the data.

Keychain: Keychain, on the other hand, provides a secure encrypted storage mechanism. It uses the device’s secure enclave and keychain services to store sensitive data such as passwords, cryptographic keys, or authentication tokens. Data stored in the Keychain is encrypted and protected using hardware-backed encryption, making it more difficult for attackers to access.

44. PushNotification Size

Remote Push Notifications: For most devices running iOS 13 and later, the maximum payload size for remote push notifications is 4 KB (4096 bytes). However, older devices running iOS 12 or earlier have a smaller limit of 2 KB (2048 bytes).

VoIP Push Notifications: For Voice over Internet Protocol (VoIP) push notifications, the payload size is limited to 5 KB (5120 bytes) on most iOS versions.

Rich Push Notifications: If you’re sending rich push notifications that include media attachments (images, videos, etc.), the maximum payload size is reduced further. The total payload size should not exceed 2 KB (2048 bytes) for iOS 12 and earlier, and 4 KB (4096 bytes) for iOS 13 and later.

45. What are types of notification

Push Notifications: Push notifications are messages that are sent from a server or backend system to a user’s device. They appear on the device’s home screen or in the notification center, even when the app is not actively being used. Push notifications are used to deliver important or time-sensitive information, such as news updates, messages, reminders, or alerts.

In-App Notifications: In-app notifications are messages that appear within the app while the user is actively using it. These notifications are typically used to provide contextual information, promote new features, offer discounts, or engage users with relevant content. In-app notifications can be shown as banners, pop-ups, or other visual elements within the app’s user interface.

Badge Notifications: Badge notifications are small numeric indicators displayed on the app’s icon on the device’s home screen. They show the number of unread messages, notifications, or other relevant data within the app. Badge notifications serve as a visual cue to attract the user’s attention and indicate that there is new content or activity to be checked.

Sound Notifications: Sound notifications are audible alerts played by the device when a notification is received. They can be customized to play specific sounds or tones associated with different types of notifications. Sound notifications are particularly useful in situations where immediate attention is required, such as urgent messages or alerts.

Alert Notifications: Alert notifications are modal pop-up windows that appear on the device’s screen, overlaying the current app or content. These notifications usually contain important information or require user interaction, such as confirmation dialogs, permission requests, or critical alerts that require immediate attention.

Silent Notifications: Silent notifications are push notifications that do not display any visual or audible alerts to the user. They are primarily used to trigger background tasks or update app content without interrupting the user. Silent notifications can be used to perform tasks like syncing data, refreshing content, or updating app states silently.

46. Retain

In Objective-C, retain is used as part of manual reference counting (MRC) to indicate that the object being referred to should be retained or kept in memory. When an object is retained, its reference count is incremented, and it will not be deallocated until the reference count reaches zero. This attribute is typically used when declaring instance variables or properties in Objective-C.

assign: In Objective-C, assign is used to declare a simple assignment of values without any automatic memory management. It is often used for primitive types or objects that should not be retained or released automatically. When an object with the assign attribute is deallocated, the reference to that object becomes a dangling pointer, potentially leading to crashes if accessed.

46. What is Associated Values?

In Swift, associated values are a feature of enumerations (enums) that allow you to associate additional data with each enum case. It allows you to attach and store different types of values along with the enum case, enabling more flexible and expressive data modeling.

47. What is Associated Type :

AssociatedType is a feature used in protocols to define a placeholder type that is associated with a conforming type. It allows the protocol to define requirements that involve types that will be specified by the conforming types. Associated types enable protocol authors to define protocols that are flexible and adaptable to different concrete types.

48. SOLID Principles

Single Responsibility Principle: Each an every class you create/change should have only one responsibility

Open Closed : Classes and Modules should be open for extension but closed for modification

Liskov’s Subsititution: Child classes should never break the parent class type definitions

Interface Segregation : The Interface or class API’s to client should have minimum information required by the client

Dependency Inversion : Class A should not depend on Class B or vice versa, both should be losely coupled

49. Downcasting ? And Upcasting

Downcasting is the process of casting a reference of a superclass to one of its subclass types. It’s used when you have a reference to a superclass and want to treat it as an instance of a more specific subclass. Downcasting is done using the as? or as! keyword.

Upcasting is the process of casting a reference of a subclass to its superclass type. It’s implicit and happens automatically when assigning an instance of a subclass to a variable or constant of its superclass type.

50. Methods available in App Delegate?

This method is called when the app finishes launching. It provides an opportunity to perform any initialization tasks and return whether the app launched successfully.

This method is called when the app becomes active, either when it is launched or when it returns to the foreground. Use this method to resume any paused tasks or update the user interface.

This method is called when the app enters the background. Use this method to save data, invalidate timers, or perform any cleanup tasks before the app is suspended or terminated.

This method is called when the app is about to terminate. Use this method to perform any final cleanup tasks before the app is closed.

This method is called after the app successfully registers for remote notifications and provides the device token. Use this method to send the device token to your server for push notification setup.

This method is called when the app fails to register for remote notifications. Use this method to handle any error scenarios during registration.

This method is called when the app receives a remote notification while it is running or in the background. Use this method to handle and process the received notification.

51. Git Fetch:

the fetch command is used to retrieve changes from a remote repository without merging them into your local branch. It allows you to update your local repository with the latest commits from the remote repository, giving you access to the latest changes made by other developers

git fetch [<remote>] [<branch>]

Fetching Changes:

52. BitCode

Bitcode is an intermediate representation of your app’s compiled code that is used by Apple’s App Store for various purposes, such as optimization and device-specific compilation.

Bitcode Generation:

When you build your Swift app using Xcode, you have the option to enable Bitcode generation. Bitcode is generated by the Swift compiler during the build process. It represents a platform-independent intermediate form of your app’s compiled code.

Benefits of Bitcode:

The primary benefit of using Bitcode is that it allows Apple to re-optimize and recompile your app’s code for specific devices or future architectures. This enables Apple to deliver performance improvements or take advantage of new features without requiring you to rebuild and resubmit your app.

App Store Submission:

When you submit your app to the App Store, you have the option to upload Bitcode along with your app binary. If you choose to include Bitcode, it gives Apple the flexibility to recompile your app’s code to match the device architecture of the user’s device at the time of installation.

Device-Specific Compilation:

When a user installs your app from the App Store, Apple’s backend infrastructure can compile the Bitcode to generate the final executable specifically optimized for the user’s device architecture. This allows for more efficient execution and can result in improved performance.

Xcode and Bitcode Support:

Xcode provides tools and settings to manage Bitcode generation and submission. You can enable Bitcode generation in the “Build Settings” of your Xcode project. Additionally, Xcode includes a “Download Debug Symbols” option that allows you to retrieve symbol information for crash reports, even if you’ve uploaded Bitcode.

53. Dependency Injection :

Dependency Injection (DI) is a design pattern in Swift (and other programming languages) that promotes loose coupling and improves the testability and flexibility of code. It involves providing dependencies to an object from the outside, rather than having the object create or manage its dependencies internally.

54. Static Dispatch and Dynamic Dispatch

Dynamic dispatch happens at runtime, and the actual method to be called is determined dynamically based on the type of the object at runtime. This allows for polymorphism and enables the use of subclass-specific implementations of methods.

Static Dispatch :

Static dispatch, also known as compile-time dispatch, occurs when the compiler knows at compile-time which method implementation to invoke based on the static type of the object. In other words, the method resolution is determined during compilation, and the compiler directly inserts the address of the method to be called.

Calling Non-Overridden Methods: When a method is called on an object, and the method is not overridden by any subclass, the compiler can determine the method to be called at compile-time. The compiler knows the actual type of the object and directly resolves the method call.

Calling final Methods: If a method is marked as final in a class, it cannot be overridden by any subclass. Since the method is guaranteed not to change during runtime, the compiler can perform static dispatch, knowing exactly which implementation to call.

Add a comment

Related posts:

GPU fiziksel sunucu

GPU fiziksel sunucuları, grafik işleme birimlerine (GPU) sahip olan özel sunuculardır. Bu sunucular, yüksek performanslı hesaplama ve grafik işleme yetenekleriyle bilgisayarların işlem gücünü…

BFFs

The first time we met, we sat with an impending assembly and the oppression of, what would feel like, hours of silence at the mercy of our headmistress, the demagogue. My best friend thought I was a…

Setting up a Business by Chance

Concept Folks was established back in 2013 — and it was unplanned for most parts. It was Eric, my husband’s uncle, who started it all in 2012. He was a seasoned property agent who approached me for…