0% found this document useful (1 vote)
3K views

Swift Interview Questions and Answers PDF

This document contains an article about Swift interview questions and answers. It provides sample questions for beginner, intermediate, and advanced levels that could be used to test a candidate's Swift knowledge. The questions cover topics like Swift syntax, optional values, classes vs structs, closures, generics, and more. Sample code is included with each question and an explanation is provided for the answers.

Uploaded by

Rajib Bose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
3K views

Swift Interview Questions and Answers PDF

This document contains an article about Swift interview questions and answers. It provides sample questions for beginner, intermediate, and advanced levels that could be used to test a candidate's Swift knowledge. The questions cover topics like Swift syntax, optional values, classes vs structs, closures, generics, and more. Sample code is included with each question and an explanation is provided for the answers.

Uploaded by

Rajib Bose
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

6/22/2016

SwiftInterviewQuestionsandAnswers

Swift Interview Questions and Answers


AntonioBelloonAugust25,2015

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
}

var tutorial1 = Tutorial()


var tutorial2 = tutorial1
tutorial2.difficulty = 2
Whatsthevalueoftutorial1.difficultyandtutorial2.difficulty?WouldthisbeanydifferentifTutorialwasa
class?Why?

SolutionInside:Answer

Show

Question#3Swift1.0orlater
view1isdeclaredwithvar,andview2isdeclaredwithlet.Whatsthedifferencehere,andwillthelastlinecompile?
import UIKit

var view1 = UIView()


view1.alpha = 0.5

let view2 = UIView()


view2.alpha = 0.5 // Will this line compile?

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

init(fullAddress: String, city: String) {


self.fullAddress = fullAddress
self.city = city
}
}

class Person {
var name: String
var address: Address

init(name: String, address: Address) {


self.name = name
self.address = address
}
}

var headquarters = Address(fullAddress: "123 Tutorial Street", city: "Appletown")


var ray = Person(name: "Ray", address: headquarters)
var brian = Person(name: "Brian", address: headquarters)
SupposeBrianmovestothenewbuildingacrossthestreet,soyouupdatehisrecordlikethis:
brian.address.fullAddress = "148 Tutorial Street"
Whatsgoingonhere?Whatswrongwiththis?

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
}
}

let thermometerClass = ThermometerClass()


thermometerClass.registerTemperature(56.0)

public struct ThermometerStruct {


private(set) var temperature: Double = 0.0
public mutating func registerTemperature(temperature: Double) {
self.temperature = temperature
}
}

let thermometerStruct = ThermometerStruct()


thermometerStruct.registerTemperature(56.0)
Thiscodefailstocompile.Where?Why?

Tip:ReaditcarefullyandthinkaboutitabitbeforetestingitinaPlayground.

SolutionInside:Answer

Show

Question#3Swift1.0orlater
Whatwillthiscodeprintoutandwhy?
var thing = "cars"

let closure = { [thing] in


print("I love \(thing)")
}

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
}

return dividend! / divisor!


}
Thiscodeworksasexpectedbuthastwoissues:
Thepreconditionscouldtakeadvantageoftheguardstatement
Itusesforcedunwrapping
Improvethisfunctionusingtheguardstatementandavoidtheusageofforcedunwrapping.

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 {
}

func showKitten(kitten: Kitten?) {


guard let k = kitten else {
print("There is no 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

Where To Go From Here?


Congratsonmakingittotheend,anddon'tfeelbadifyoudidn'tactuallyknowalltheanswers!
SomeofthesequestionsareprettycomplicatedandSwiftisarich,expressivelanguage.There'salottolearn.Moreover,
Applekeepsimprovingitwithnewfeatures,soeventhebestofusmaynotknowitall.
TogettoknowSwiftorbuilduponwhatyoualreadyknow,besuretocheckoutourindepth,tutorialrichbook,Swiftby
Tutorials,orsignupforourhandsontutorialconferenceRWDevCon!
Ofcourse,theultimateresourceforallaspectsofSwiftistheofficialTheSwiftProgrammingLanguagebyApple.
Attheendoftheday,usingalanguageisthebestwaytolearnit.JustplaywithitinaPlaygroundoradoptitinarealproject.
Swiftworks(almost)seamlesslywithObjectiveC,sobuildingonanexistingprojectyoualreadyknowisanexcellentwayto
learntheinsandouts.
Thanksforvisitingandworkingthroughthesequestions!Feelfreetochimeinbelowwithyourquestions,problemsand
discoveries.Iwouldn'tmindifyouwantedtoposesomeofyourownchallengestoo.Wecanalllearnfromeachother.See
youintheforums!

AntonioBello
Antonioisaveterancodewriterwhostartedtappingonkeyboardswhenmemorywas
measuredinbytesinsteadofgigabytes,storagewasanoptionaladdon,andthemost
usedlanguagewasBASIC.
TodayhelovesdevelopingiOSapps,writingnode.jsbackends,andhenevermissesa
chancetolearnsomethingnew.
HefindsSwiftaveryexpressivelanguage,andstillthinksObjectiveCisgreatand
unconventional.

https://www.raywenderlich.com/110982/swiftinterviewquestionsanswers

11/11

You might also like