Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Andropov

macrumors 6502a
Original poster
May 3, 2012
746
992
Spain
I'm starting to learn programming and I've chosen to use Swift, but I'm having a little trouble with something. I'm trying to do a simple word-counter app, but I don't know how to relate the variables (var) in the AppDelegate to variables in the ViewController.swift (so I can put them into a label).

How do I use a var (which is a string) from the AppDelegate in the ViewController.swift so I can show it in a label? The other problem (though I guess it'll be done in a similar way) is how to import the text written (by the user) in a textfield to the ViewController.swift and back to the AppDelegate.

Thanks in advance
 
You probably don't want to be using the AppDelegate to store data, create a new class to store data and pass it to the view controller to then set the label.

OR if you are just playing about then use the ViewController file to declare the variable and then set the label from there.

Code:
let myText = "Some text here"
myLabel.text = myText
 
The line above shows an error in Xcode: Use of unresolved identifier 'myLabel'
How should I fix it?

You need to declare myLabel somewhere, IE,

Code:
@IBOutlet var myLabel : NSTextField

Note: Although I'm reading the manual, I'm not currently enrolled in a developer program so don't have access to Xcode 6 yet. Startup I'm at is in the process of enrolling in iOS Enterprise right now, so I'll have access soon. The point being, I'm not quite sure if my syntax is right because I've only read about it, I haven't actually written anything myself yet.

You might need

Code:
import cocoa

for NSTextField to be recognized.

Oh wait, you're on iOS, so you might need a UITextField instead. Not sure what the corresponding import statement would be... you're probably working from a template so already have it.
 
I'm starting to learn programming and I've chosen to use Swift...

I think this is a bad idea. Swift is just too new to use to start learning programming. It is beta, as is Xcode 6. Therefore, there's a good chance you'll encounter bugs and issues that as someone new to programming you might not be able to detect if an issue you are encountering is caused by you or caused by the tools you are using. You should be looking at learning programming using established technologies rather than something so bleeding-edge.
 
You need to declare myLabel somewhere, IE,

Code:
@IBOutlet var myLabel : NSTextField

Note: Although I'm reading the manual, I'm not currently enrolled in a developer program so don't have access to Xcode 6 yet. Startup I'm at is in the process of enrolling in iOS Enterprise right now, so I'll have access soon. The point being, I'm not quite sure if my syntax is right because I've only read about it, I haven't actually written anything myself yet.

You might need

Code:
import cocoa

for NSTextField to be recognized.

Oh wait, you're on iOS, so you might need a UITextField instead. Not sure what the corresponding import statement would be... you're probably working from a template so already have it.

Yeah, it works, I used (I've had also tried using a UILabel before starting this topic, same result):

Code:
@IBOutlet var myTextField : UITexfield

And it worked to the point I was able to connect it to the TextField in the IB, but when I tried to change the text inside to a simple string (later I'll change the string to a var, but I want to keep it simple until it works):

Code:
myTextField.text = "Hello World"

Then Xcode shows a "Expected declaration" error. However, looking at the Apple's Swift documentations, it looks like I'm writing it right, so maybe the problem is the place where I've wrote it (I wouldn't be surprised, since the documentation already assumes that you know how to code in Objective-C), so here's the full ViewController.swift

Code:
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myTextField : UITextField
    myTextField.text = "Hello World" //Shows "Expected Declaration" error
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

Thanks for your help

I think this is a bad idea. Swift is just too new to use to start learning programming. It is beta, as is Xcode 6. Therefore, there's a good chance you'll encounter bugs and issues that as someone new to programming you might not be able to detect if an issue you are encountering is caused by you or caused by the tools you are using. You should be looking at learning programming using established technologies rather than something so bleeding-edge.

Yes, you may be right, the problem is that when I tried to learn to program in Objective-C (last summer) I found it too difficult and I didn't see a lot of progress after some time, so I abandoned it. However, with Swift, although I obviously have some troubles too, I'm actually seeing more progress with less time and effort.

Maybe I should wait until Xcode 6 is out of beta and/or try Objective-C again.
 
Yeah, it works, I used (I've had also tried using a UILabel before starting this topic, same result):

Code:
@IBOutlet var myTextField : UITexfield

And it worked to the point I was able to connect it to the TextField in the IB, but when I tried to change the text inside to a simple string (later I'll change the string to a var, but I want to keep it simple until it works):

Code:
myTextField.text = "Hello World"

Then Xcode shows a "Expected declaration" error. However, looking at the Apple's Swift documentations, it looks like I'm writing it right, so maybe the problem is the place where I've wrote it (I wouldn't be surprised, since the documentation already assumes that you know how to code in Objective-C), so here's the full ViewController.swift

Code:
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myTextField : UITextField
    myTextField.text = "Hello World" //Shows "Expected Declaration" error
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

Thanks for your help



Yes, you may be right, the problem is that when I tried to learn to program in Objective-C (last summer) I found it too difficult and I didn't see a lot of progress after some time, so I abandoned it. However, with Swift, although I obviously have some troubles too, I'm actually seeing more progress with less time and effort.

Maybe I should wait until Xcode 6 is out of beta and/or try Objective-C again.

Put it in viewDidLoad instead.

As far as when to learn this...

I'm planning on wrapping up reading the Swift manual, getting enrolled in a developer program, and getting Xcode 6 all before the end of this week. This weekend I'll layout the sections that I want to cover in a beginner friendly book, and the order I'd like to cover them, and then I'd like to start writing the book. I already have a lot of stuff I've written (always incomplete - never published) to introduce beginners to other languages, so I just need to adapt it all to Swift. I'll probably have it all done and on stores sometime in July or August - probably before Apple actually releases a non-beta of Xcode 6.

Anyways, once that's released, that'll be a good time to start learning. Once I get going I'll probably post drafts online to get feedback. I'm thinking I'll make those available for free when I post them, I'll edit them as I get feedback, and I'll take them down once I feel the feedback is positive enough.

I'm anticipating a gold rush, and whether everyone else digs up gold or dirt, I want to be the one selling the shovels.
 
Last edited:
Yes, you may be right, the problem is that when I tried to learn to program in Objective-C (last summer) I found it too difficult and I didn't see a lot of progress after some time, so I abandoned it.

Objective-C is not the only way to learn programming. In fact, there are plenty of other "first" languages that will introduce you to the concepts of programming that seem better adapted to the first time programmer.
 
Already tried, says only instance properties can be declared 'IBOutlet'

Always post the code you tried.

We can guess what code caused the error, but it's better if you post your exact code and the actual error message.

For example, based on the error message, you probably put the variable declaration AND the assignment of a string into viewDidLoad. This would make the variable automatic, not instance. But I'm just guessing.
 
Always post the code you tried.

We can guess what code caused the error, but it's better if you post your exact code and the actual error message.

For example, based on the error message, you probably put the variable declaration AND the assignment of a string into viewDidLoad. This would make the variable automatic, not instance. But I'm just guessing.

Ok, thanks for the advice. BTW, you were right, I corrected it and then Xcode doesn't show any error. However, when opening it in the iOS 8 simulator, it crashes, says: SetAppThreadPriority: setpriority failed with error 45


Here's the code:
Code:
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myTextField : UITextField
    
    override func viewDidLoad() {
        super.viewDidLoad()    //Shows: "Thread 1: breakpoint 1.1"
        myTextField.text = "Hello World"

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}
 
Ok, thanks for the advice. BTW, you were right, I corrected it and then Xcode doesn't show any error. However, when opening it in the iOS 8 simulator, it crashes, says: SetAppThreadPriority: setpriority failed with error 45


Here's the code:
Code:
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var myTextField : UITextField
    
    override func viewDidLoad() {
        super.viewDidLoad()    //Shows: "Thread 1: breakpoint 1.1"
        myTextField.text = "Hello World"

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

Mine works using the code above, make sure you are using a Text Field on the Storyboard and make sure its referencing outlet is connected to the view controller by myTextField.
 
Mine works using the code above, make sure you are using a Text Field on the Storyboard and make sure its referencing outlet is connected to the view controller by myTextField.

Looks like is an Xcode problem. Creating a new Xcode project and copy-pasting all the code in each file solved the problem.

Here's one more question: I've created a different .swift file where I have a function called "countCharacters":

Code:
import Foundation

let fullConstant = "Type something!"

func countCharacters(inout fullConstant: String) {
    var myVariable = ""
    let FirstPart = "There are "
    let LastPart = " characters"
    let fullConstant = ""
    var numberOfCharacters = countElements(myVariable)
    switch myVariable {
    case "I like oranges" :
        let fullConstant = String("I like oranges too") + String(". BTW, there are ") + String(numberOfCharacters) + String(LastPart)
    default :
        switch numberOfCharacters {
        case 0 :
            let fullConstant = "There isn't any character yet"
        case 1 :
            let fullConstant = "There is just one character"
        default :
            let fullConstant = FirstPart + String(numberOfCharacters) + LastPart
            
        }
    }
}

I want to call the function from a IBAction (tapping a button) in the ViewController.swift. How do I do it? I can't find anything in the documentation...
 
I want to call the function from a IBAction (tapping a button) in the ViewController.swift. How do I do it? I can't find anything in the documentation...

I have had to change your code slightly because it yours doesn't make sense and didn't work, however please see below (note that you will have to connect the IBAction I have created to the button on the storyboard) but this works. In essence you are just importing (this is done automatically now in swift) the other file.

This is only one of a few ways to achieve it, there are others such as class functions, instance methods as well as keeping all related view controller functionality in one class file such as the ViewController.swift file and not separating it out.

ViewController.swift

Code:
//
//  ViewController.swift


import UIKit

class ViewController: UIViewController {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func clickMe(sender : AnyObject) {
        var fullConstant = "Test"
        countCharacters(&fullConstant)
        println(fullConstant)
    }


}

OtherClass.swift

Code:
//
//  OtherClass.swift
//

import Foundation

func countCharacters(inout fullConstant: String) {

    let FirstPart = "There are "
    let LastPart = " characters"
    var numberOfCharacters = countElements(fullConstant)
        switch numberOfCharacters {
        case 0 :
            fullConstant = "There isn't any character yet"
        case 1 :
            fullConstant = "There is just one character"
        default :
            fullConstant = FirstPart + String(numberOfCharacters) + LastPart
        }
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.