Reputation: 717
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?
Upvotes: 9
Views: 17201
Reputation: 5359
You can create a Utils class
, filled with static variables/functions
For example:
class Utils {
static func convert(to variable: String) -> Int? {
... do some stuff to variable
return newVariable
}
}
// on your ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
if let converted = Utils.convert(to: "123") {
print(converted)
}
}
By making use of static functions you can access them anywhere and everywhere to reuse them.
------------------
Another way is to make use of extensions
For example:
extension String {
var toInt: Int? {
return Int(self)
}
}
// on your ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
if let converted = "SomeValue".toInt {
print(converted)
}
}
Both of these can be used in many different scenarios.
Upvotes: 3
Reputation: 23883
You need to use singletons
.
Create NSObject in User.swift
import Foundation
import UIKit
class User: NSObject {
var name: String = 0
func getName() -> String{
name = "Erik Lydecker"
return name
}
}
Then initialize your object and trigger the method there.
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let instanceOfUser = User()
instanceOfUser.getName() // Erik Lydecker
}
}
Upvotes: 5
Reputation: 4839
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 ... }
Upvotes: 11