Search Your Question

Explain collections in Swift

Following are different types of collections in Swift:

Array
Set
Dictionary

Let's understand one by one : 

1. Array

  • Most common and Widely used data type. 
  • Ordered collection of similar types of data. 

Declaration: 

var normalArray = [Int]() // declaring an empty                        Int array like this

  • The array can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type when we declare an array but we can also specify the type

var normalArray = [2,3,4,5]
var normalArray: [Int] = [2,3,4,5]

You also can declare an array with some repeated values or using one or more arrays

var normalArray = Array(repeating: 1, count: 3) //initialize normalArray with three ones var normalArray = arrayOne + arrayTwo //initialize normalArray with addign arrayOne & arrayTwo
  • Insert elements into an Array: We can insert an element at the end of the array or in a valid position.
normalArray.append(12) //append element at the end of array
normalArray += [100.0] //append at the end
normalArray.insert(12, at: 0) //insert element at 0 position. This position value should be n to n-1 if array have n number of elements.
  • Access Elements of Array: We can access the element of an array using a subscript syntax, passing the index value into it. Also swift provided a list of methods to get values and check different parameters.
normalArray[2]  //return second element from array
normalArray.count // return the number of elements in array
normalArray.isEmpty // return false if array is empty
normalArray.capacity // return the number of elements in array
normalArray.first //get the first element from array
normalArray.last //get the last elements from array
normalArray.max() //get the max element from array
normalArray.min() //get the min element from array
normalArray.sorted() // sort the array
normalArray.reversed() //reverse an array
normalArray.shuffled() //shuffle the elements of an array
  • Replace elements of Array: Array value can set or replace in a specific index or for a range of the index.
normalArray[2] = 1 // replace the value in second index of arraynormalArray[1...3] = [12, 23, 34] // set first to third position value as 12, 23 &34
  • Remove elements from Array: Array elements can remove from different ways & different positions.
normalArray.removeAll() // remove allelement from array
normalArray.removeFirst() // remove first element from array
normalArray.removeLast() // remove last element from array
normalArray.remove(at: 2) //remove second element from arraynormalArray.removeLast(1) // remove the second element from the end index of arraynormalArray.removeFirst(2) // remove the thirdelement from the start index of the array
  • Iterate over the array: Every element of an array can be traverse using loop
for i in 0..<normalArray.count{
print(normalArray[i])
}
or
for item in normalArray{
print(item)
}

2. Dictionary

  • Can hold multiple unordered data in key-value pairs. 
  • Each value is associated with a unique key and any value from the dictionary can access with the associated key with it.

  • Declaration: 
var normalDictionary = [Int: String]() 
// an empty "normalDictionary" with Int type key & String type value

  • The key-value pair of a dictionary can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type of key-value pair when we declare a dictionary but we can also specify the type

var normalDictionary = [1: "John", 2: "Doe"]
var normalDictionary : [Int: String] = [1: "John", 2: "Doe"]
  • Insert elements into a Dictionary: We can insert a value into the dictionary using a key. If the key already exists it will replace the previous value for this key elsewhere it will add a new value.
normalDictionary[3] = "Mihalos"  // Add a value "Mihalos" for key "3"
  • Access Elements of Dictionary: We can access the elements of a dictionary by using the key. Also swift provided a list of methods to get values and check different parameters.
normalDictionary[2] //return the value of second key-value pair in dictionary normalDictionary.count // return the number of elements in dictionarynormalDictionary.isEmpty  // return false if dictionary is emptynormalDictionary.capacity  // return the number of elements in dictionarynormalDictionary.first  //get the first element from dictionarynormalDictionary.max { a, b in a.value < b.value}  // return key-value pair for maximum valuenormalDictionary.min()  { a, b in a.value < b.value}  // return key-value pair for minimumvaluenormalDictionary.sorted( by: { $0.0 < $1.0 }) // reurn an sorted array of dictionarynormalDictionary.reversed()  //return key-value pair in reverse ordernormalDictionary.shuffled()  //shuffle the key-value pair of dictionary
  • Replace elements from a Dictionary: A value for a key is simply replaced by putting a new value for that key. We also can use “updateValue” method to replace the value for any key. But Remember “updateValue” method returns the previous value as output.
normalDictionary[3] = "Mike"
normalDictionary.updateValue("Duke", forKey: 3)
  • Remove elements from Dictionary: Dictionary elements can be removed in a different way.
normalDictionary[3] = nil  // remove key-value pair for key "3"
normalDictionary.removeAll() // remove all element from dictionary arraysimpleDictionary.removeAll(keepingCapacity: true) remove all elements with keeping the capacity or not
  • Iterate over the Dictionary: Every key-value pairs of a dictionary can be traverse using loop
for (key, value) in normalDictionary {
print(key, value)
}

Instead of key-value pair we also can access only key or value from dictionary like this

for key in normalDictionary.keys{
print(key)
}
for value in normalDictionary.values{
print(value)
}

We also can get the keys and values of a dictionary as an array.

let keys = [Int](normalDictionary.keys)  // return all the keys as an array
let values = [String](normalDictionary.values) //return all the values as an array

3. Set

  • Set is an unordered collection of the same type of data. 
  • The main characteristic of the set is, set can not have any duplicate elements.

  • Declaration: You can declare an empty Int type set like this
var normalSet = Set<Int>() // an empty Int type set

  • The set can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type when we declare a set but we can also specify the type

var normalSet = Set([10, 20, 30, 40, 20])
varnormalSet: Set<String> = ["John", "Doe", "Hi", "John"]

You also can declare a set with some repeated values but you will get a single value for those repeated value cause set didn’t store any duplicate element.

var normalSet = Set(repeatElement(1, count: 3)) // Initialize set with three ones but set will have only one into it.
  • Insert elements into a set: We can insert an element at the end of the array or in a valid position.
normalSet.insert(12) // //append element at the end of set
  • Access Elements of a set: Like array you cannot access set elements using subscript syntax but you can check an element is in the set or not. Also swift provided a list of methods to get values and check different parameters.
normalSet.contains(2)  // check an element is in the set or not
normalSet.count // return the number of elements in set
normalSet.isEmpty // return false if set is 
empty normalSet.capacity   // return the number of elements in setnormalSet.first //get the first element from set
normalSet.max() //get the max element from set
normalSet.min() //get the min element from set
normalSet.sorted() // sort the set
normalSet.reversed() // reverse set
normalSet.shuffled() // shuffle set elements
  • Remove elements: Set elements can remove from different way & from different positions also.
normalSet.removeFirst() // remove first element from set
normalSet.remove(1) // remove from a specific index
normalSet.removeAll() // remove all elements from set
normalSet.removeAll(keepingCapacity: true) // remove all elements with keeping the capacity or not
  • Iterate over the set: Every element of a set can be traverse using loop
for data in normalSet {
print(data)
}

The set type didn’t have any order so if you want to traverse in any order you can do it by swift provided methods

for data in normalSet.sorted() {
print(data)
}
for data in normalSet.reversed() {
print(data)
}
  • Different set operations: You also can perform different set operations within two sets and each of those operations will create a new set.
normalSet2.union(normalSet3).sorted()  // perform union opertion within normalSet2 & normalSet3
normalSet2.intersection(normalSet3) // perform intersection within two set
normalSet2.subtracting(normalSet3) // perform subtracting
normalSet2.symmetricDifference(normalSet3) // perform symmetricDifference
normalSet2.isSubset(of: normalSet3) // check one set is subset of snother or not
normalSet2.isSuperset(of: normalSet3) // check superset or not
normalSet2.isDisjoint(with: normalSet3) // check disjoint or not

There are some more interview questions answers for collections in this site. Visit here

Difference between Value type and Reference type

Value Types

value type instance is an independent instance and holds its data in its own memory allocation. There are a few different value types: Struct, Enum, Tupple.

Struct

Let’s experiment with struct and prove that they’re value types:

Add the following code to your playground:

// 1
struct Car {
    let brand: String
    var model: String
}

// 2
var golf = Car(brand: "Volkswagen", model: "Golf")
// 3
let polo = golf

// 4
golf.model = "Golf 2019"

// 5
print(golf)
print(polo)

In the code above, you will:

  • Create a Car struct with brand and model properties.
  • Create a new instance of Car named golf.
  • Create a copy of the golf instance, named polo.
  • Change the golf.model variable to Golf 2019
  • Print the 2 different instances. The first print statement prints Car(brand: "Volkswagen", model: "Golf 2019") in the Console. The second one prints Car(brand: "Volkswagen", model: "Golf"). Even if polo is a copy of golf, the instances remain independent with their own unique data copies.

With this simple playground, we’ve confirmed that structs are indeed value types.

Enum

To check that enums are value types, add this code to the playground:

// 1
enum Language {
    case italian
    case english
}

// 2
var italian = Language.italian
// 3
let english = italian

// 4
italian = .english

// 5
print(italian)
print(english)

In the code above, you will:

  • Create a Language enum with italian and english cases.
  • Create a new instance of Language for the italian language.
  • Create a copy of the italian instance, named english.
  • Change the italian instance to english.
  • Print the two different instances. The first print statement prints english, and the second one prints italian. Even if english is a copy of italian, the instances remain independent.

Tuple

The last value type that we'll explore is tuple. A tuple type is a comma-separated list of zero or more types, enclosed in parentheses. You can access its values using the dot (.) notation followed by the index of the value.

You can also name the elements in a tuple and use the names to access the different values.

Add the following code to the playground:

// 1
var ironMan = ("Tony", "Stark")
// 2
let parent = ironMan

// 3
ironMan.0 = "Alfred"

// 4
print(ironMan)
print(parent)

In the code above, you will:

  • Create an ironMan tuple with the strings Tony and Stark.
  • Create a copy of the ironMan instance, named parent.
  • Change the ironMan.0 index to Alfred.
  • Print the 2 different instances. The first print, prints ("Alfred", "Stark") and the second one, prints ("Tony", "Stark"). Again, the instances remain independent.

You can now be certain that structsenums, and tuples are value types

When to Use Value Types

Use value types when comparing instance data with == makes sense.
== checks if every property of the two instances is the same.
With value types you always get a unique, copied instance, and you can be sure that no other part of your app is changing the data under the hood. This is especially helpful in multi-threaded environments where a different thread could alter your data.

Use a value type when you want copies to have an independent state, and the data will be used in code across multiple threads.

In Swift, ArrayString, and Dictionary are all value types.

Reference Types

In Swift, reference type instances share a single copy of their data, so that every new instance will point to the same address in memory. A typical example is a classfunction, or closure.

To explore these, add a new function to your playground:

func address<T: AnyObject>(of object: T) -> Int {
    return unsafeBitCast(object, to: Int.self)
}

This function prints the address of an object, which will help you check whether you're referencing the same instance or not.

Class

The first reference type that you'll look at is a class.

Add the following code to your playground:

// 1
class Dog: CustomStringConvertible {
    var age: Int
    var weight: Int

    // 2
    var description: String {
        return "Age \(age) - Weight \(weight)"
    }

    // 3
    init(age: Int, weight: Int) {
        self.age = age
        self.weight = weight
    }
}

// 4
let doberman = Dog(age: 1, weight: 70)
// 5
let chihuahua = doberman

// 6
doberman.age = 2
// 7
chihuahua.weight = 10

// 8
print(doberman)
print(chihuahua)

// 9
print(address(of: doberman))
print(address(of: chihuahua))

In the code above, you will:

  • Create a new class named Dog, that conforms to CustomStringConvertible to print the custom descriptions of the object.
  • Define the custom description of the object.
  • Create a new init function. This is needed because, unlike a struct, a class doesn't automatically create an initialization function based on the variables of the object.
  • Create a doberman instance of Dog.
  • Create a copy of doberman, named chihuahua.
  • Change the doberman.age t2.
  • Change the chihuahua.weight t10.
  • Print the description of the two different instances. The first print, prints Age 2 - Weight 10, and the second one prints the same; Age 2 - Weight 10. This is because you're actually referencing the same object.
  • Print the address of the two different instances. With these prints, you'll be sure that you're referencing the same address. You'll see that both print statements print the same value.

You can rest assured that a class is a reference type.

Functions and Closures

closure is used to refer to a function along with the variables from its scope that it encapsulates. Functions are essentially closures that store references to variables in their context.

Take a look at the code below:

let closure = { print("Test") }
func function() -> (){ print("Test") }

closure()
function()

They both do the same thing.

You can find more info about closures in Swift's docs.

When to Use Reference Types

Use a reference type when comparing instance identity with ===makes sense. === checks if two objects share the same memory address.

They’re also useful when you want to create a shared, mutable state.

As a general rule, start by creating your instance as an enum, then move to a struct if you need more customization, and finally move to class when needed.

iOS 15 Release date , features - All answers related to iOS 15


iOS 15 Release date , features



FAQ for iOS 15


Q. Which is latest iOS version?
A. iOS 15 is latest iOS Version.

Q. What is iOS 15 release date?
A. iOS 15 is released on 20 September, 2021 worldwide.

Q. Is there any version after iOS 15 ?
A. iOS 15.1 beta version is released on 21 September, 2021.

Q. What is iOS 15 release date in India?
A. iOS 15 is released on 20 Sepember, 2021 in India.

How to install iOS 15 now


Step 1: Goto settings menu in iPhone

Step 2: Scroll down and tap on General

Step 3: Check if iOS 15 update is there or not.

Step 4: If yes, tap on the Download option displayed on the screen.

Step 5: Apple also provides the option to install the update while you are asleep. Select the best-suited option and install the iOS 15 update.

Once the iOS 15 update is installed, your iPhone will boot up. It will take some time due to update size is almost 3 GB. Before starting with the installation process, below are a few tips to keep in mind.

Tips to keep in mind before installing iOS 15

–Connect your iOS Device with stable high speed wifi.

–As iOS 15 update is almost 3 GB update, keep such space in memory

–Installation will take around half an hour. So keep your iOS device in charging mode.


Important features in iOS 15 updates for daily usse


  • Facetime

iOS 15 includes a new features for FaceTime. It will help apple to compete with other online meeting service like JioMeet, Zoom, Microsoft Team, etc.

Features in Facetime:
Spatial Audio support
Portrait mode for videos
Grid view for videos
Join FaceTime calls from the web on Android and Windows
FaceTime links
SharePlay for sharing content during FaceTime, including screen sharing, music, and more

  • Messages

Apple has also announced new features for Messages, including new ways to easily access content that people send you. Shared Stacks will bring over content from Messages to Photos app.

  • Notifications


Notification design is changed and anyone can choose to view summary.
When you enable DND, your status will be shown to other people via the Messages app
Notification design has been changed with large icons.
You can set different “Focus” status that change your Home Screen, notification preferences, and more.

  • Photos

Photos app now includes OCR capability. Due to this, it enables covert from image to text with artificial intelligence.
Photos can also be searched in spotlight. So it can be easily searched.

  • Weather

The Weather app has been revamped with lots of new data.
Layout design of the Weather app changes based on the weather in your current location.

  • Safari

iOS 15 brings a completely new design to Safari. Controls are brought to the bottom of the screen so that they are easier to reach with one hand.

There is a new, compact tab bar that floats at the bottom of the screen so that users can easily swipe between tabs, and it also contains a Smart Search field. Tab Groups allow users to save their tabs in a folder and sync across the iPhone, iPad, and Mac. In addition, there is a new tab overview grid view.

Users can simply pull down a web page to refresh it and there is now support for voice search. Safari also gains a customizable start page and mobile web extensions for the first time.


These are some important features that normal users can see changes. Otherwise apple has changed in many in-built application but it is not daily use for every people.

If you have any doubt or any question related iOS 15 release, please comment on box below.

What is push notification payload maximum size?

Apple Push Notification service (APNs) refuses a notification if the total size of its payload exceeds the following limits:

  • FCM - 2 Kb
  • VOIP Notification - 5 kb
  • For all other remote notification - 4 kb

What is trailing closure?

 If the last parameter to a function is a closure, Swift lets you use special syntax called trailing closure syntax. Rather than pass in your closure as a parameter, you pass it directly after the function inside braces.

To demonstrate this, here’s our travel() function again. It accepts an action closure so that it can be run between two print() calls:

func travel(action: () -> Void) {

    print("I'm getting ready to go.")

    action()

    print("I arrived!")

}

Because its last parameter is a closure, we can call travel() using trailing closure syntax like this:

travel() {

    print("I'm driving in my car")

}

In fact, because there aren’t any other parameters, we can eliminate the parentheses entirely:

travel {

    print("I'm driving in my car")

}

Trailing closure syntax is extremely common in Swift, so it’s worth getting used to.

Difference between method and function

Methods belong to classes, structs, and enums, whereas functions do not.

Methods always belong to a data type, they have a concept of self that functions do not. This is a special value passed in by Swift, and it refers to whatever instance the method was called on.

Swift uses the same keyword, func, for both functions and methods.

Difference between type method and Instance method?

Type Method: We can call the method using Struct, Class, or Enum name. The method can be static or Class for making such methods. Static method can not be override but class method can be override.

Instance Method: We can call normal method using making instance of strcut or class. This methods are called instance method.

Difference between Swift and Objective C

 


 SWIFT  

 OBJECTIVE C


Swift is a general-purpose, high-level programming language that is highly concerned about safety, and performance.

Objective C is a general-purpose language that is considered a superset of C language it was designed with the aim of providing object-oriented capabilities.


It was developed by Chris Lattner with eventual collaboration with other programmers at Apple.

It was developed by Brad Cox and Tom Love at their company Stepstone.


It was influenced by Objective C, Rust, Ruby, and Python.

It was influenced by C and Smalltalk.


Swift first appeared on the year 2014.

Objective C first appeared on the year 1984.


Swift is a static type.

Objective C is dynamic type.


Swift is apache licensed open-source project.

Objective C is licensed under General Public License.


It only has classes.

It has both Structs and classes.


It was designed for building apps for iOS, Mac, Apple TV, and Apple Watch.

Objective C was designed to be Smalltalk messaging features.


Swift polymorphism does not exist directly.

Polymorphism in Objective C exists directly in compile time.


It uses true and false values.

It uses YES and NO values and also BOOl.


Swift has multiple types of templates than Objective C.

Objective C lacks templates than Swift.

What is remote config in firebase

Change the behavior and appearance of your app without publishing an app update, at no cost, for unlimited daily active users.

Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. When using Remote Config, you create in-app default values that control the behavior and appearance of your app. Then, you can later use the Firebase console or the Remote Config backend APIs to override in-app default values for all app users or for segments of your user base. Your app controls when updates are applied, and it can frequently check for updates and apply them with a negligible impact on performance.

What is KVO?

Key-value observing is the ability for Swift to attach code to variables, so that whenever the variable is changed the code runs. It’s similar to property observers (willSet and didSet ), except KVO is for adding observers outside of the type definition.


KVO isn’t terribly nice in pure Swift code, because it relies on the Objective-C runtime – you need to use @objc classes that inherit from NSObject, then mark each of your properties with @objc dynamic.


For example, we could create a Car class like this:


@objc class Car: NSObject {

    @objc dynamic var name = "BMW"

}


let bmw= Car()

You could then observe that user’s name changing like this:


bmw.observe(\Car.name, options: .new) { car, change in

    print("I'm now called \(car.name)")

}

That asks BMW to watch for new values coming in, then prints the person’s name as soon as the new value is set.


To try it out, just change the car's name to something else:


bmw.name = "Mercedese"

That will print “I’m now called Mercedese.”


Although KVO is unpleasant in pure Swift code, it’s better when working with Apple’s own APIs – they are all automatically both @objc and dynamic because they are written in Objective-C.


However, one warning: even though large parts of UIKit might work with KVO, this is a coincidence rather than a promise – Apple makes no guarantees about UIKit remaining KVO-compatible in the future.