Swift Interview Questions and Answers PDF
Swift Interview Questions and Answers PDF
SwiftInterviewQuestionsandAnswers
Ifyou'renewhere,youmaywanttosubscribetomyRSSfeedorfollowmeonTwitter.Thanksforvisiting!
EventhoughSwiftisonlyayearold,itsalreadyoneofthemost
popularlanguages.Itssyntaxlooksveryeasysoeasythat
whenitwasannouncedJavaScriptdevelopersfeltliketheimage
totheright.
Inreality,Swift,isacomplexlanguage.Itembracesbothobject
orientedandfunctionalapproaches,anditsstillevolvingwith
eachnewrelease.
TheresalottoSwiftbuthowcanyoutesthowmuchyouve
learned?Inthisarticle,theraywenderlich.comTutorialTeamand
IhaveputtogetheralistofsampleSwiftinterviewquestions.
Youcanusethesequestionstointerviewcandidatestotesttheir
Swiftknowledge,ortestyourown!Andifyoudontknowthe
answer,dontworry:eachquestionhasasolutionsoyoucan
learn.
Thequestionsaresplitintotwosections:
Writtenquestions:Goodtoincludeinatakebyemail
programmingtest,sinceitsometimesinvolveswritingabit
ofcode.
Verbalquestions:Goodtoaskoverthephoneorinafacetofaceinterview,astheycanbeansweredmoreeasily
verbally.
Also,eachsectionissplitintothreelevels:
Beginner:SuitableforabeginnertoSwift,whosreadabookortwoonthesubjectandstartedworkingwithSwiftin
theirownapps.
Intermediate:Suitableforsomeonewhosgotastronginterestinlanguageconcepts,whohasbeenreadingalotof
blogpostsaboutSwiftandexperimentingwithitfurther.
Advanced:Suitableforthebestofthebestonlyfolkswhoenjoythoroughlyexploringthelanguage,challenging
themselves,andusingthecuttingedgetechniques.
Ifyouwanttotryansweringthesequestions,IsuggestyoukeepaPlaygroundopentoplaywiththecodeattachedtothe
questionbeforeanswering.AnswersweretestedagainstXcode7.0beta6.
Ready?Buckleup,itstimetogo!
Note:Specialthankstoraywenderlich.comTutorialTeammembersWarrenBurton,GregHeo,MikaelKonutgan,Tim
Mitra,LukeParham,RuiPeres,andRayWenderlichwhohelpedmecomeupwithsomeofthesequestions,andtest
themfordifficultylevel.
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
1/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Written Questions
Beginners
Hellothere,padowan.Illstartyouoffwiththebasics.
Question#1Swift1.0orlater
Whatsabetterwaytowritethisforloopwithranges?
for var i = 0; i < 5; i++ {
print("Hello!")
}
SolutionInside:Answer
Show
Question#2Swift1.0orlater
Considerthefollowing:
struct Tutorial {
var difficulty: Int = 1
}
SolutionInside:Answer
Show
Question#3Swift1.0orlater
view1isdeclaredwithvar,andview2isdeclaredwithlet.Whatsthedifferencehere,andwillthelastlinecompile?
import UIKit
SolutionInside:Answer
Show
Question#4Swift1.0orlater
Thiscodesortsanarrayofnamesalphabeticallyandlookscomplicated.Simplifyitandtheclosureasmuchasyoucan.
let animals = ["fish", "cat", "chicken", "dog"]
let sortedAnimals = animals.sort { (one: String, two: String) -> Bool in
return one < two
}
SolutionInside:Answer
Show
Question#5Swift1.0orlater
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
2/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Thiscodecreatestwoclasses,AddressandPerson,anditcreatestwoinstancestorepresentRayandBrian.
class Address {
var fullAddress: String
var city: String
class Person {
var name: String
var address: Address
SolutionInside:Answer
Show
Intermediate
Nowtostepupthedifficultyandthetrickiness.Areyouready?
Question#1Swift2.0orlater
Considerthefollowing:
var optional1: String? = nil
var optional2: String? = .None
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
3/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Whatsthedifferencebetweenniland.None?Howdotheoptional1andoptional2variablesdiffer?
SolutionInside:Answer
Show
Question#2Swift1.0orlater
Heresamodelofathermometerasaclassandastruct:
public class ThermometerClass {
private(set) var temperature: Double = 0.0
public func registerTemperature(temperature: Double) {
self.temperature = temperature
}
}
Tip:ReaditcarefullyandthinkaboutitabitbeforetestingitinaPlayground.
SolutionInside:Answer
Show
Question#3Swift1.0orlater
Whatwillthiscodeprintoutandwhy?
var thing = "cars"
thing = "airplanes"
closure()
SolutionInside:Answer
Show
Question#4Swift2.0orlater
Heresaglobalfunctionthatcountsthenumberofuniquevaluesinanarray:
func countUniques<T: Comparable>(array: Array<T>) -> Int {
let sorted = array.sort(<)
let initial: (T?, Int) = (.None, 0)
let reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
return reduced.1
}
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
4/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Ituses<and==operators,soitrestrictsTtotypesthatimplement,theComparableprotocol.
Youcallitlikethis:
countUniques([1, 2, 3, 3]) // result is 3
RewritethisfunctionasanextensionmethodonArraysothatyoucanwritesomethinglikethis:
[1, 2, 3, 3].countUniques() // should print 3
SolutionInside:Answer
Show
Question#5Swift2.0orlater
Here'safunctiontocalculatedivisionsgiventotwo(optional)doubles.Therearethreepreconditionstoverifybefore
performingtheactualdivision:
Thedividendmustcontainanonnilvalue
Thedivisormustcontainanonnilvalue
Thedivisormustnotbezero
func divide(dividend: Double?, by divisor: Double?) -> Double? {
if dividend == .None {
return .None
}
if divisor == .None {
return .None
}
if divisor == 0 {
return .None
}
SolutionInside:Answer
Show
Oh,hithere.You'renowatthemidpointandIseeyou'regoingstrong.Shallweseehowyoufarewithsomeadvanced
questions?
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
5/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Advanced
Question#1Swift1.0orlater
Considerthefollowingstructurethatmodelsathermometer:
public struct Thermometer {
public var temperature: Double
public init(temperature: Double) {
self.temperature = temperature
}
}
Tocreateaninstance,youcanobviouslyusethiscode:
var t: Thermometer = Thermometer(temperature:56.8)
Butitwouldbenicertoinitializeitthisway:
var thermometer: Thermometer = 56.8
Canyou?How?Hint:ithastodowithconvertibles,butnotconvertibleslikeCamarosandMustangs:)
SolutionInside:Answer
Show
Question#2Swift1.0orlater
Swifthasasetofpredefinedoperatorsthatperformdifferenttypesofoperations,suchasarithmeticorlogic.Italsoallows
creatingcustomoperators,eitherunaryorbinary.
Defineandimplementacustom^^poweroperatorwiththefollowingspecifications:
TakestwoIntsasparameters
Returnsthefirstparameterraisedtothepowerofthesecond
Ignorespotentialoverflowerrors
SolutionInside:Answer
Show
Question#3Swift1.0orlater
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
6/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Canyoudefineanenumerationwithrawvalueslikethis?Why?
enum Edges : (Double, Double) {
case TopLeft = (0.0, 0.0)
case TopRight = (1.0, 0.0)
case BottomLeft = (0.0, 1.0)
case BottomRight = (1.0, 1.0)
}
SolutionInside:Answer
Show
Question#4Swift2.0orlater
ConsiderthefollowingcodethatdefinesPizzaasastructandPizzeriaasaprotocol,withanextensionthatincludesa
defaultimplementationforthemethodmakeMargherita():
struct Pizza {
let ingredients: [String]
}
protocol Pizzeria {
func makePizza(ingredients: [String]) -> Pizza
func makeMargherita() -> Pizza
}
extension Pizzeria {
func makeMargherita() -> Pizza {
return makePizza(["tomato", "mozzarella"])
}
}
You'llnowdefinetherestaurantLombardisasfollows:
struct Lombardis: Pizzeria {
func makePizza(ingredients: [String]) -> Pizza {
return Pizza(ingredients: ingredients)
}
func makeMargherita() -> Pizza {
return makePizza(["tomato", "basil", "mozzarella"])
}
}
ThefollowingcodecreatestwoinstancesofLombardi's.Whichofthetwowillmakeamargheritawithbasil?
let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis()
lombardis1.makeMargherita()
lombardis2.makeMargherita()
SolutionInside:Answer
Show
Question#5Swift2.0orlater
Thefollowingcodehasacompiletimeerror.Canyouspotwhereandwhyithappens?
struct Kitten {
}
print(k)
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
7/11
6/22/2016
SwiftInterviewQuestionsandAnswers
}
Hint:Therearethreewaystofixit.
SolutionInside:Answer
Show
Verbal Questions
You'regood,butyoucan'tclaimjedistatusyet.Anybodycanfigureoutthecode,buthowdoyoudowithmoreopenended
questionsoftheoryandpractice?
ToanswersomeofthemyoustillmightneedtoplaywiththecodeinaPlayground.
Beginners
Question#1Swift1.0orlater
Whatisanoptionalandwhatproblemdooptionalssolve?
SolutionInside:Answer
Show
Question#2Swift1.0orlater
Whenshouldyouuseastructure,andwhenshouldyouuseaclass?
SolutionInside:Answer
Show
Question#3Swift1.0orlater
Whataregenericsandwhatproblemdotheysolve?
SolutionInside:Answer
Show
Question#4Swift1.0orlater
Thereareafewcaseswhenyoucan'tavoidusingimplicitlyunwrappedoptionals.When?Why?
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
8/11
6/22/2016
SwiftInterviewQuestionsandAnswers
SolutionInside:Answer
Show
Question#5Swift1.0orlater
Whatarethevariouswaystounwrapanoptional?Howdotheyrateintermsofsafety?
Hint:Thereareatleastsevenways.
SolutionInside:Answer
Show
Intermediate
Timetorachetupthechallengehere.Seemsyou'redoingjustfinesofar,butlet'sseeifyoumakeitthroughthesequestions.
Question#1Swift1.0orlater
IsSwiftanobjectorientedlanguageorafunctionallanguage?
SolutionInside:Answer
Show
Question#2Swift1.0orlater
WhichofthefollowingfeaturesareincludedinSwift?
1.Genericclasses
2.Genericstructs
3.Genericprotocols
SolutionInside:Answer
Show
Question#3Swift1.0orlater
InObjectiveC,aconstantcanbedeclaredlikethis:
const int number = 0;
HereistheSwiftcounterpart:
let number = 0
Isthereanydifferencebetweenthem?Ifyes,canyouexplainhowtheydiffer?
SolutionInside:Answer
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
Show
9/11
6/22/2016
SwiftInterviewQuestionsandAnswers
Question#4Swift1.0orlater
Todeclareastaticpropertyorfunctionyouusethestaticmodifieronvaluetypes.Here'sanexampleforastructure:
struct Sun {
static func illuminate() {}
}
Forclasses,it'spossibletouseeitherthestaticortheclassmodifier.Theyachievethesamegoal,butinrealitythey're
different.Canyouexplainhowtheydiffer?
SolutionInside:Answer
Show
Question#5Swift1.0orlater
Canyouaddastoredpropertybyusinganextension?Explain.
SolutionInside:Answer
Show
Advanced
Ohboy,you'reacleverone,aren'tyou?It'stimetostepitupanothernotch.
Question#1Swift1.2
InSwift1.2,canyouexplaintheproblemwithdeclaringanenumerationwithgenerictypes?TakeforexampleanEither
enumerationwithtwogenerictypesTandV,withTusedastheassociatedvaluetypeforaLeftcaseandVforaRight
case:
enum Either<T, V> {
case Left(T)
case Right(V)
}
Protip:InspectthiscaseinanXcodeproject,notinaPlayground.AlsonoticethatthisquestionisrelatedtoSwift1.2
soyou'llneedXcode6.4.
SolutionInside:Answer
Show
Question#2Swift1.0orlater
Areclosuresvalueorreferencetypes?
SolutionInside:Answer
Show
Question#3Swift1.0orlater
TheUInttypeisusedtostoreunsignedintegers.Itimplementsthefollowinginitializerforconvertingfromasignedinteger:
init(_ value: Int)
However,thefollowingcodegeneratesacompiletimeerrorexceptionifyouprovideanegativevalue:
let myNegative = UInt(-1)
Knowingthatanegativenumberisinternallyrepresented,usingtwo'scomplementasapositivenumber,howcanyou
convertanIntnegativenumberintoanUIntwhilekeepingitsmemoryrepresentation?
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
Show
10/11
6/22/2016
SwiftInterviewQuestionsandAnswers
SolutionInside:Answer
Show
Question#4Swift1.0orlater
CanyoudescribeasituationwhereyoumightgetacircularreferenceinSwift,andhowyou'dsolveit?
SolutionInside:Answer
Show
Question#5Swift2.0orlater
Swift2.0featuresanewkeywordtomakerecursiveenumerations.HereisanexampleofsuchanenumerationwithaNode
casethattakestwoassociatedvaluetypes,TandList:
enum List<T> {
case Node(T, List<T>)
}
What'sthatkeyword?
SolutionInside:Answer
Show
AntonioBello
Antonioisaveterancodewriterwhostartedtappingonkeyboardswhenmemorywas
measuredinbytesinsteadofgigabytes,storagewasanoptionaladdon,andthemost
usedlanguagewasBASIC.
TodayhelovesdevelopingiOSapps,writingnode.jsbackends,andhenevermissesa
chancetolearnsomethingnew.
HefindsSwiftaveryexpressivelanguage,andstillthinksObjectiveCisgreatand
unconventional.
https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers
11/11