When you dive into .map and .flatMap ocean, you may be confused what is the difference. Consider such example:

let arr = [1,2,3,4,5,6]
print(arr.map{ return String($0 * 2)+"x" })
print(arr.flatMap{ return String($0 * 2)+"x" })

Both print’s, will give you same result:

["2x", "4x", "6x", "8x", "10x", "12x"]

So why bother? The main details between them, is that flatMap will skip nil values and unwraps them, so the example:

let mapArr = arr.map{ (string:Int) -> String? in
    if string < 2 {
        return nil
    }
    return String(string * 2)+"x"
}
print(mapArr)
let mapArr2 = arr.flatMap{ (string:Int) -> String? in
    if string < 2 {
        return nil
    }
    return String(string * 2)+"x"
}
print(mapArr2)

will give following results:

[nil, Optional("4x"), Optional("6x"), Optional("8x"), Optional("10x"), Optional("12x")]
["4x", "6x", "8x", "10x", "12x"]

As you can see now .map output are all optionals with nil as first value is skipped. In .flatMap each value is unwrapped to String and there is no nil values at all.

Testing is good practice, but sometimes you may get into trap. Opposite to Objective-C, in Swift 2.x you don’t need to add each file to your test target, even more – you should not do this at all!

Using Swift 1.x developers had to make every testable class and methods public, which was very annoying. Now, all you have to do, is use:

@testable import ProjectName

in each of your test files (this is required for both unit testing and UI testing). But there is one catch – what if your project name contains spaces like “My First Swift Project”? Fortunately there is simple solution, in most cases just replace space with underscore, but if you want to be sure, go to your app’s target, then “Build settings”, and search for “Module name” – this is string you should use in import.

Swift unit/UI testing

Sooner or later you will face with “Invalid predicate: nil RHS”. What does it mean? Fortunately solution is very simple, somewhere in your code, you are using NSPredicate with “CONTAINS” while your search text is nil. All you have to do is make sure to check and validate text entered by user.

The common mistake is using more then one “@” placeholders, while having only one parameter.