Group Group Group Group Group Group Group Group Group

raywenderlich.com Forums

Swift Interview Questions and Answers

A handy list of Swift interview questions to prepare for a job interview, to test a candidate's Swift knowledge, or to check your own skills! :]


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1699-swift-interview-questions-and-answers

Intermediate #4 solution updated for Swift 3

extension Array where Element: Comparable {
    func countUniques() -> Int {
        let sorted = self.sorted()
        let initial: (Element?, Int) = (.none, 0)
        let reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
        return reduced.1
    }
}

Intermediate #5 solution updated for Swift 3

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

// - - - - - Verbal Questions - - - - -
//Question #5 - Swift 1.0 or later
//What are the various ways to unwrap an optional? How do they rate in terms of safety?
//Hint: There are at least seven ways.

//Declaration
var x:String? = "Test"

//1 Safely unwrapping via binding

if let y = x {
	print("x was successfully unwraped and is = \(y)")
}
//x=nil

//2 guard statement

guard let y = x else{
	print("x has no value")
	fatalError()
}

//3 Force Unwrap

print(x!)

//4 Coalescing nil values

x=nil

var z = x ?? "No value for x"

//5 Implicity unwrapping

var d:String! = "Test2"

//6 Optional chaining

var e = x?.range(of: "Te")
var f = d?.range(of: "Te")
print(e)
print(f)

//7 Optional pattern

if case let g? = x {
	print(g)
}

Thanks a lot.
from China.

Question #2 - Swift 1.0 or later

This is outdated. For the swift 3 or later you need to create precedence Group

precedencegroup PowerPrecedence {
associativity: right // just for ( 2 * (4 * 3)) when we have three input
higherThan: MultiplicationPrecedence
}

infix operator ^^ : PowerPrecedence

func ^^(x: Int, y: Int) -> Int {
let x = Double(x)
let y = Double(y)
let power = pow(x, y)
return Int(power)
}

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]