Passing function as a argument to another function

Swift is new language on the block, I recently started playing with it. Until now,Objective-C was prefered choice for iOS apps, but future is going to be more and more swift. So today is really day 2 with swift but I wrote some example code to test out the feature of Swift that allows passing function as an argument to another function, and I just can’t stop thinking about it. This programming language concept is usually supported in language where functions are first class citizens like JavaScript, so I have used this before , but the way it is supported in swift is just amazing and smooth. Take a look at the below code

func popNumbers(numbers : [Int],condition : (Int -> Bool) ) -> [Int] {
var numbersToBePoped = [Int]()
for number in numbers {
if condition(number) {
return numbersToBePoped

func lessThanFive(number:Int) -> Bool{
return number < 5

func oddNumber(number : Int ) -> Bool{
return number % 2 != 0

func threeDigitNumber(number : Int ) -> Bool{
return number >= 100

var resultArray = popNumbers([12,2,135,45,3,209], lessThanFive)
var resultArray2 = popNumbers([12,2,135,45,3,209], oddNumber)
var resultArray3 = popNumbers([12,2,135,45,2,209], threeDigitNumber)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s