简体   繁体   中英

how to access a variable outside a for loop in swift

do {
    let results = try context.executeFetchRequest(request)

    for result in results as! [NSManagedObject] {
        var  savepassword = result.valueForKey("savePassword")!     
    }
} catch {

}

// what I want is to be able to access the variable out here
// savepasword

You need to declare savePassword outside the loop. You should note that if there are multiple objects returned from your query then you will end up with the value from the last object in the array. This may or may not be what you want

var savepassword : String?

do {
    let results = try context.executeFetchRequest(request)

    for result in results as! [NSManagedObject] {
        savepassword = result.valueForKey("savePassword") as? String    
    }
} catch {

}

if let savepassword = savepassword {
   // Do something with savepassword
}
var any: Any
do {
    let results = try context.executeFetchRequest(request)
    any = results
 } catch {

}
for result in any as! [NSManagedObject] {
    var  savepassword = result.valueForKey("savePassword")!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM