SoFunction
Updated on 2025-04-10

Swift interview questions and answers sorting out

Preface

Swift has been born for more than a year and has become one of the most popular languages ​​at present. Although its syntax is simple and easy to use, Swift is actually a very complex language. Because it is not only an object-oriented but also a functional programming language. This article mainly introduces some common interview questions in Swift. You can use these questions to ask interviewers, or you can use them to test the Swift knowledge you currently have. If you don’t know the answer to the question, don’t worry too much, because there are corresponding answers below each question.

1. Give an array, ask to write a function to exchange two elements in the array

Two X programmers:

Very simple, just write the following results

func swap(_ nums: inout [Int], _ p: Int, _ q: Int) {
 let temp = nums[p]
 nums[p] = nums[q]
 nums[q] = temp 
}

Ordinary programmer:

First, communicate with the interviewer, what type of array is it? The interviewer will say, please. An ordinary programmer smiled and wrote the following code

func swap<T>(_ nums: inout [T], _ p: Int, _ q: Int) {
 let temp = nums[p]
 nums[p] = nums[q]
 nums[q] = temp 
}

Art programmer:

What type of array is it when communicating with the interviewer? What are the other requirements and restrictions? The interviewer will say that this is a Swift interview question. The literary programmer understood it, so he wrote the following answer

func swap<T>(_ nums: inout [T], _ p: Int, _ q: Int) {
 (nums[p], nums[q]) = (nums[q], nums[p])
}

At the same time, write corresponding tests on the above code, detect various boundary situations, and then confirm that it is correct, then I will say that I have completed this question.

This question seems simple, but actually examines the programmer's awareness of question review, communication, and testing. Technically examines the generics of Swift and the properties of Tuple.

2. What's wrong with the following code

public class Node {
 public var value: Int
 public var prev: Node?
 public var post: Node?

 public init(_ value: Int) {
  = value
 }
}

Answer: It should bevar prev orvar post Add weak to the front.

Reason: On the surface, there is no problem with the above code. But as soon as I write this, the problem comes:

let head = Node(0)
let tail = Node(1)
 = tail
 = head

At this time, head and tail point to each other, forming a retain cycle.

3. Implement a function, the input is any integer, and the output is to return the input integer + 2

Many people write this question like this:

func addTwo(_ num: Int) -> Int {
 return num + 2
}

Next, the interviewer will say, what if I want to achieve + 4? The programmer thought about it and defined another method:

func addFour(_ num: Int) -> Int {
 return num + 4
}

At this time, the interviewer will ask, what if I want to implement the operation of returning +6, +8? Can you define the method only once? The correct way to write it is to use the Cauchy features of Swift:

func add(_ num: Int) -> (Int) -> Int {
 return { val in
 return num + val
 }
}

let addTwo = add(2), addFour = add(4), addSix = add(6), addEight = add(8)

4. Simplify the following code

func divide(dividend: Double?, by divisor: Double?) -> Double? { 
 if dividend == nil { 
 return nil 
 } 
 if divisor == nil { 
 return nil 
 } 
 if divisor == 0 { 
 return nil
 } 
 return dividend! / divisor!
}

This question examines guard let statement and optional chaining, the best answer is

func divide(dividend: Double?, by divisor: Double?) -> Double? { 
 guard let dividend = dividend, let divisor = divisor, divisor != 0 else {
 return nil
 }

 return dividend / divisor
}

5. What will the following function print?

var car = "Benz" 
let closure = { [car] in 
 print("I drive \(car)")
} 
car = "Tesla" 
closure()

Because closure has declared that the car has been copied into ([car]), the car in clousre is a local variable and is no longer related to the car outside, so "I drive Benz" will be printed.

At this time, the interviewer smiled slightly and slightly modified the question as follows:

var car = "Benz" 
let closure = {
 print("I drive \(car)")
} 
car = "Tesla" 
closure()

At this time, closure does not declare the assignment copy of car, so closure still uses the global car variable, and "I drive Tesla" will be printed out

6. What will the following code print?

protocol Pizzeria { 
 func makePizza(_ ingredients: [String])
 func makeMargherita()
} 

extension Pizzeria { 
 func makeMargherita() { 
 return makePizza(["tomato", "mozzarella"]) 
 }
}

struct Lombardis: Pizzeria { 
 func makePizza(_ ingredients: [String]) { 
 print(ingredients)
 } 
 func makeMargherita() {
 return makePizza(["tomato", "basil", "mozzarella"]) 
 }
}

let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis() 
()
()

Answer: Print out the following two lines

["tomato", "basil", "mozzarella"]
["tomato", "basil", "mozzarella"]

In the Lombardis code, the makeMargherita code is rewritten, so the makeMargherita in Lombardis is always called.

Going further, we will take the protocol Pizzeriafunc makeMargherita()Delete, the code becomes

protocol Pizzeria {
 func makePizza(_ ingredients: [String])
}

extension Pizzeria {
 func makeMargherita() {
 return makePizza(["tomato", "mozzarella"])
 }
}

struct Lombardis: Pizzeria {
 func makePizza(_ ingredients: [String]) {
 print(ingredients)
 }
 func makeMargherita() {
 return makePizza(["tomato", "basil", "mozzarella"])
 }
}

let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis()
()
()

At this time, the following results are printed:

["tomato", "mozzarella"]
["tomato", "basil", "mozzarella"]

Because lombardis1 is Pizzeria,makeMargherita()There is a default implementation, and at this time we call the default implementation.

7. What is the difference between defining constants in Swift and defining constants in Objective-C?

Most people think there is no difference because it seems that there is no difference when written.

OC defines constants like this:

const int number = 0;

Swift defines constants like this:

let number = 0

First of all, the first difference is that const is used in OC to represent constants, while in Swift, let is used to determine whether it is a constant.

The above difference goes further. The constant types and values ​​indicated by const in OC are determined at the time of compilation; while in Swift, let only indicates that constants (can only be assigned once), and their types and values ​​can be static or a dynamic calculation method, which are determined at runtime.

8. What is the difference between struct and class in Swift? Take an example in the application

struct is the value type and class is the reference type.

Anyone who has seen WWDC knows that struct is recommended by Apple because it is more secure than class when passing and copying small data models, and is especially useful when requesting multi-threaded and network.

Let's take a look at a simple example:

class A {
 var val = 1
}

var a = A()
var b = a
 = 2

At this time, the val of a is also changed to 2, because a and b are both reference types, essentially they point to the same memory. The solution to this problem is to use struct:

struct A {
 var val = 1
}

var a = A()
var b = a
 = 2

At this time A is struct, the value type is b and a are different things, changing b has no effect on a.

9. Is Swift an object-oriented or functional programming language?

Swift is both an object-oriented and functional programming language.

Swift is Object-oriented because Swift supports encapsulation, inheritance, and polymorphism of classes. From this point of view, it is almost no different from pure object-oriented languages ​​like Java.

Swift is a functional programming language because Swift supports map, reduce, filter, flatmap and other methods that remove intermediate states and mathematical functional formulas, and emphasizes calculation results rather than intermediate processes.

Summarize

The above is all about the Swift interview questions. I hope the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.