Helpful code for interviews in Swift?

I was wondering if any Swift programmers had some helpful snipets of code for the interviews?

Here are a couple situational tricks I have learned.

If you need to store counters for values in a Hash Map.

var map: [SomeType: Int] = [:]
map[value, default: 0] += 1

This will add the desired key to the Hash Map if it does not exist and initialize the value to 0. If a value does exist, the value will be incremented by 1.

Another little trick.

Strings in Swift are not simple to index. And retreiving the count of a String or iterating through a String in Swift is a linear operation.

So when you get a String problem, ask the interviewer if it is okay if you take the Strings into the function as an Array of Characters instead.

func isSomething(_ stringOne: [Character], _ stringTwo: [Character]) -> Bool {
	return true
}

Cheers!

David

Comments (3)