Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode way to print "Hello World" when button is clicked in OS X Swift application?

I'm an experienced Java and Visual Studio developer, but I am just starting out with Swift & Xcode. I am an utter noob, who has never written a line of objective-c. I want to print "Hello World" when I click on the button that I have added in the "Storyboard" view for my application. But I cannot figure out how to get Xcode to insert an event method anywhere in the swift source code files. I’ve read %60 of "The Swift Programming Language", but I don't know any of the cocoa apis yet. Most examples reference objective-c files that do not exist in a Swift application. I also am not using the iOS platform, so I suspect some examples I've pasted (i.e. @IBAction func buttonTapped ) fail because they are not applicable to OS X applications.

I would appreciate a little help :)

like image 645
Charlweed Avatar asked Apr 03 '15 23:04

Charlweed


People also ask

How do you print an object in Swift?

Writing Output with print() You use the print() function in Swift to write a string to standard output, which is typically the Console in Xcode. Here's an example: print(“So long and thanks for all the fish!”) The above example can't get any easier.

How do you print a variable in Swift?

In Swift, you can print a variable or a constant to the screen using the print() function.


1 Answers

You just need to add a label and a button to your window. Then you need to connect your label outlet to your code.

enter image description here

You need to connect your button to your viewController also:

enter image description here

import Cocoa

class ViewController: NSViewController {

    @IBOutlet var strLabel: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func printHello(sender: AnyObject) {
        strLabel.stringValue = "Hello World !!!"
    }

}
like image 52
Leo Dabus Avatar answered Sep 26 '22 23:09

Leo Dabus