访问超出范围 Swift 的变量 [英] Accessing a variable that is out of scope Swift

查看:24
本文介绍了访问超出范围 Swift 的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是基本的东西,但我似乎无法理解.我有一个函数,它获取日期选择器值,将其转换为字符串,将其分配给变量,然后更新标签文本.

I know the is elementary stuff but I can't seem to get this. I have a function that takes the date pickers value, converts it to a string, assigns it to a variable, and them updates a labels text.

我希望能够在函数之外访问该变量,以便在 prepareForSegue 中使用它.到目前为止,我已经尝试创建一个全局变量并在调用函数时对其进行更新,但这似乎不起作用,并且我尝试在函数中返回值但我一定做错了,因为它也不起作用.

I want to be able to access that variable outside of the function so I can use it in prepareForSegue. So far I have tried making a global variable and updating it when the function is called but that didn't seem to work, and I have tried returning the value in the function but I must have done that wrong because it didn't work either.

功能:

func datePickerChanged(datePicker:UIDatePicker) {
    var dateFormatter = NSDateFormatter()

    dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    var strDate = dateFormatter.stringFromDate(datePicker.date)
    dateTimeLabel.text = strDate
}

我想从函数中取出 strDate.非常感谢任何帮助!

I want to get strDate out of the function. Any help is much appreciated!

推荐答案

你可以用不同的方式做到这一点.你可以在方法上使用 inout 参数来允许方法更新参数,像这样:

You can do this in different ways.. You can use an inout parameter on a method to allow the method to update the parameter, like this:

var aString = ""

func doStuffWithA(inout theString: String) {

theString = "Groovy"
}

doStuffWithA(&aString) // changes aString to "Groovy"

或者你可以在方法之外声明属性:

Or you can declare the property outside of the method:

class SomeClass {
    var someString: String = ""

    func doStuff() {
        self.someString = "Groovy"
    }
 }

如果你只想要一个 segue,你可以在 performSegueWithIdentifier 上传递对象,像这样:

If you want this just for a segue, you can pass the object on performSegueWithIdentifier, like this:

func doStuff() {

    var aString = "Groovy"
    performSegueWithIdentifier("someSegue", sender: aString)

}

// Then here you can use it and assign it as a property on the next view controller

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "someSegue" {

         guard let aString = sender as? String else {

         return
         }

         let nextVC = segue.destinationViewController as! SomeVC
         nextVC.someProperty = aString
    }
}

这篇关于访问超出范围 Swift 的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆