Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

Pass variables from one ViewController to another in Swift

I have a calculator class, a first ViewController to insert the values and a second ViewController to show the result of the calculation. Unfortunately I get a error called "Can't unwrap Optional.None" if I click the button. I know it's something wrong with the syntax, but I don't know how to improve it.

The button in the first Viewcontroller is set to "Segue: Show (e.g. Push)" in the storyboard to switch to the secondViewController if he gets tapped.

the calculator class is something like:

class Calculator: NSObject {

    func calculate (a:Int,b:Int) -> (Int) {
        var result = a * b
        return (result)
    }
}

The Viewcontroller calls the function, inserts a/b and wants to change the label which is located in the secondviewcontroller:

class ViewController: UIViewController {

@IBAction func myButtonPressed(sender : AnyObject) {
    showResult()
}

var numberOne = 4
var numberTwo = 7

var myCalc = Calculator()

func showResult () {
    var myResult = myCalc.calculate(numberOne, b: numberTwo)
    println("myResult is (String(myResult))")
    var myVC = secondViewController()
    myVC.setResultLabel(myResult)
}

And here is the code of the secondViewController

class secondViewController: UIViewController {

@IBOutlet var myResultLabel : UILabel = nil

func setResultLabel (resultValue:Int) {
    myResultLabel.text = String(resultValue)
}

init(coder aDecoder: NSCoder!)
{
    super.init(coder: aDecoder)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift, everything is public by default. Define your variables outside the classes:

import UIKit

var placesArray: NSMutableArray!

class FirstViewController: UIViewController {
//
..
//
}

and then access it

import UIKit

class TableViewController: UITableViewController {
//
placesArray = [1, 2, 3]
//
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...