Use functions from other files in Swift Xcode

ios, swift, xcode

Solution

Easy. You just create a new Swift file into your Xcode project (File - New - File - Swift file or just ⌘-N) and put your functions and classes there. No need to import anything in your view controller file as both files are part of the same package and thus see each others functions and types (unless marked as private).

func parseHtml(url: NSURL) -> String { ... your code goes here ... }

Problem

How can I write a function in a separate swift file and use it (import it) to my ViewController.swift file? I have written a lot of code and all of the code is in the ViewController.swift file, I really need to make this look good and place functions on separate files, for cleaner code. I have functions dealing with parsing HTML, functions dealing with ordering results, presenting results, responding to user actions, etc. Many thanks for any help! ``` if let htmlString = String(contentsOfURL: checkedUrl, encoding: NSUTF8StringEncoding, error: nil) { // Parsing HTML let opt = CInt(HTML_PARSE_NOERROR.value | HTML_PARSE_RECOVER.value) var err : NSError? var parser = HTMLParser(html: htmlString, encoding: NSUTF8StringEncoding, option: opt, error: &err) var bodyNode = parser.body // Create an array of the part of HTML you need if let inputNodes = bodyNode?.findChildTags("h4") { //inputNodes is an array with all the "h4" tag strings for node in inputNodes { let result = html2String(node.rawContents) println("Nyheter: \(result)") } } ``` When I add that function to a separate swift file, how can I use it in my ViewDidLoad method using a "shorthand"? A short keyword that grabs that chunk of code and use it?

Original source