Accessing a variable that is out of scope Swift(访问超出范围 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 的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问超出范围 Swift 的变量
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01