user2636197
user2636197

Reputation: 4122

Must I import Foundation when making a struct dictionary in Swift?

I have made a simple Swift file that constains some data like bellow:

import Foundation    

struct someData {
    let stringsAsInts: [name: String, value: Int] = [
        "zero" : 0,
        "one" : 1,
        "two" : 2,
        "three" : 3,
        "four" : 4,
        "five" : 5,
        "six" : 6,
        "seven" : 7,
        "eight" : 8,
        "nine" : 9
    ]
}

I then fetch that data in my VC by calling

let somedata = someData()

But must I include import Foundation in the file containing the struct? It works without it when I test at least.

Upvotes: 0

Views: 498

Answers (1)

jscs
jscs

Reputation: 64002

You only need Foundation imported if you want to use its features. One such feature would be the various NSString methods, like componentsSeparatedByString(_:). A Swift String is not bridged to NSString without importing Foundation: NSString doesn't even exist as far as that code is concerned, and so neither do those methods.

Another example is to be able to refer to bridged types, like String <=> NSString or Array <=> NSArray, using AnyObject, for example when processing results from a Parse backend. Without Foundation imported, and the associated bridging, String and Array are instances of structs, not of classes.

If you're using only native Swift types and don't need to call Foundation-only methods on them, you don't need to import the Foundation module.

Upvotes: 2

Related Questions