import UIKit
import CoreData
var i = 9
var b = Calculate // i want to use that 'Calculate' variable here and same for other 'percentage' var
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {........
.....................
......................
..................
var request = NSFetchRequest(entityName: "Entity")
request.returnsObjectsAsFaults = false;
// request.predicate = NSPredicate(format: " = %@", txt2.text!)
request.predicate = predicate
let results:NSArray = try context.executeFetchRequest(request) as! [NSManagedObject]
//request.predicate = predicate
if (results.count > 0){
var res = results[0] as! NSManagedObject
txt1.text = res.valueForKey("txt1") as! String
//.text = res.valueForKey("password") as! String
print("atendence = \(results.count)")
print("percentage = \(100*results.count/30)")
print(results.count)
var calculate = 100*results.count/30
var percentage = Float(calculate)
txt4.text = "\(percentage)%"
txt2.text = "\(results.count)"
txt3.text = "\(100*results.count/30)"
................................
.......................}
我想在Viewcontrollerclass之外使用这两个变量var百分比和var计算 对不起,如果没有正确询问,或者我无法澄清我的问题,因为我是全新的
答案 0 :(得分:0)
不要这样做。
应该封装所有数据 在类之外使用带有静态变量的结构。
struct Global {
static var i = 9
static var calculate : Float = 0.0
}
使用
访问变量let x = Global.calculate
答案 1 :(得分:0)
您可以为要全局访问的变量创建如下的共享实例。
import UIKit
class globalVariables {
class var sharedInstance: globalVariables {
struct Static {
static var instance: globalVariables?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = globalVariables()
}
return Static.instance!
}
var a: String = ""
var b: String = ""
}
在任何viewControllers中,您都可以像
一样访问它globalVariables.sharedInstance.a
globalVariables.sharedInstance.b