Search code examples
iosswift2foundation

Swift and Foundation relationship


As a newcomer to iOS Development i want to understand the relationship between Swift 2 and Foundation Framework

I already know that Swift is just a programming language and Foundation is a framework build on Objective-C.

What i don't understand is when i need to use Foundation classes or just stay at pure Swift.

For eg. when i have a Swift string do i always need to inherit from NSString for functionality i can't find in pure Swift strings?

Yesterday i was looking for a case-insensitive comparison between two Swift string. One of the solutions i found was that:

var a : String = "Cash"
var b  : String = "cash"

if(a.caseInsensitiveCompare(b) == NSComparisonResult.OrderedSame){
    println("voila")
}

This bring me a lot of frustration. How can a Swift string has a function(caseInsensitiveCompare) that doesn't exist in pure Swift?

Did the string inherit it from somewhere and how?

Please give me an overall explanation for when i need the foundation as a superset of Swift. Which part of foundation are no longer needed by me as a developer who skip Objective-C for Swift?


Solution

  • How can a Swift string has a function(caseInsensitiveCompare) that doesn't exist in pure Swift?

    It's because you imported Foundation (or UIKit, which includes Foundation) and because Swift String is bridged to Foundation NSString. This causes many (but not all) NSString methods to spring to life for String.

    If you had not imported Foundation, you would not have been able to do what you did: caseInsensitiveCompare would not have been present.