Some useful Foundation styles in Swift

Tram Ho

If anyone has ever programmed iOS, they must have seen through import Foundation and usually we only use familiar classes such as Data, URLSession, NSString… However, there are still some anonymous, less well-known classes. but also very useful in some specific problems where we don’t need to “Reinvent The Wheel” I will share the following :

NSScanner

NSScanner will retrieve numbers and strings from an original string (similar to the scanf function in C):

There are many other variations of Scanner such as scanString, scanDouble and scanHexInt that we can apply to certain data types.

NSCountedSet

Many times we can face problems that require you to keep track of the number of an element like an anagram problem:

Elements can be added multiple times with countedSet.add(element) and the counter can be checked using the countedSet.count(element) function. If the counter is 0, the element is removed from the Set.

NSOrderSet

We often use Set to store elements that are not duplicated, NSOrderSet works similar to Set but in a certain direction.

CFBinaryHeap

Heaps are an efficient way to implement priority queue structures, it will take a long time to install BinaryHeap so CFBinaryHeap is here to save you.

Although so cool, to install CFBinaryHeap, we will have to manage a lot of pointers. So we can use MCBinaryHeap (wrapper) to make it easier to install and use:

Through this article, I hope that I and everyone know their existence.

Reference:

– https://swiftrocks.com/useful-obscure-foundation-types-in-swift.html
– https://www.developer.apple.com/documentation/foundation/nsscanner
– https://developer.apple.com/documentation/foundation/nscountedset
– https://developer.apple.com/documentation/foundation/nsorderedset
– https://github.com/matthewcheok/MCBinaryHeap

Share the news now