2016-08-24 6 views
0

Ich bin ziemlich neu in Swift.Access Array außerhalb der Funktion in Swift

(a) Ich konnte die Tabellenansicht verwenden, um Zahlen aus einem Array in eine Tabelle zu laden.

(b) Ich konnte eine Textdatei aus dem Internet lesen und in ein Array laden.

Ich möchte jedoch das Array in (b), das aus der Web-Textdatei erstellt wird, in (a) angezeigt werden, die die Tabellenansicht ist.

Es scheint keine Kommunikation zwischen Abschnitt (a) und (b) in meinem Code.

Könnten Sie bitte helfen?

//MAIN CLASS 

import UIKit 

//CHUNK 0 
class ViewController: UITableViewController { 

var candies = [Candy]() 


//CHUNK 1 
override func viewDidLoad() { 

super.viewDidLoad() 

// CHUNK 1.2 
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.saifahmad.com/A.txt")!) 
httpGet(request){ 
      (data, error) -> Void in 
      if error != nil { 
       print(error) 
      } else { 
       //print(data)//PRINTING ALL DATA TO CONSOLE 
       let delimiter = "\t" // Read a tab-delimited text file 

       // self.items = [] 
       let lines:[String] = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] 

       var ar = [Double]() 

       for line in lines { 
        var values:[String] = [] 
        if line != "" { 
         values = line.componentsSeparatedByString(delimiter) 
         // Put the values into the tuple and add it to the items array 
         let str = (values[1])//CHOOSE THE COLUMN TO PRINT (0, 1, 2) 
         // Convert string to double 
         let db = NSNumberFormatter().numberFromString(str)?.doubleValue 
         ar.append(db!) 
        } 
       } 
       dump(ar) // THIS ARRAY 'AR' PRINTS OK HERE BUT CANNOT BE ACCESSED IN CHUNK 1.3 
      } 
    } 
    // CHUNK 1.2 


    //CHUNK 1.3 
    // CANNOT ACCESS ARRAY 'AR' OF CHUNK 1.2 HERE 
    let ar2: [Double] = [0, 0.004, 0.008, 0.012, 0.016, 0.02, 0.024, 0.028, 0.032, 0.036, 0.04] 
    for nn in ar2 { 
     self.candies.append(Candy(name: String(format:"%.4f", nn))) 
    } 
    //CHUNK 1.3 


} 
//CHUNK 1 


//CHUNK 2 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
//CHUNK 2 


//CHUNK 3 
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.candies.count 
} 
//CHUNK 3 


//CHUNK 4 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell 
    var candy : Candy 
    candy = candies[indexPath.row] 
    cell.textLabel?.text = candy.name 
    return cell 
} 
//CHUNK 4 


//CHUNK 5 
func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) { 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(request){ 
     (data, response, error) -> Void in 
     if error != nil { 
      callback("", error!.localizedDescription) 
     } else { 
      let result = NSString(data: data!, encoding: 
       NSASCIIStringEncoding)! 
      callback(result as String, nil) 
     } 
    } 
    task.resume() 
} 
//CHUNK 5 


} 
//CHUNK 0 



//CANDY CLASS 
import Foundation 

struct Candy { 
let name : String 
    } 

This is the screenshot of the tableview which loads fine from the local array. However, I want the table to load from the Web text file!

Antwort

0

Also Ihr Problem ist, dass Sie das Array ar in Ihrem Verschluss für die Anforderung erklären. Es existiert also nur in der Schließung. Sie haben zwei Möglichkeiten: Erstellen Sie ein Array außerhalb von viewDidLoad und legen Sie es fest, sobald Sie das komplette Array haben, und verwenden Sie didSet, um Bonbons zu setzen, oder Sie können alle Einstellungen für Bonbons innerhalb des Closings vornehmen (siehe unten). Ich würde sowieso ein didset mit Süßigkeiten setzen, um Ihr TableView neu zu laden.

var candies = [Candy]() { 
    didSet { 
     tableView.reloadData() 
    } 
} 

override func viewDidLoad() { 

    super.viewDidLoad() 

    // CHUNK 1.2 
    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.saifahmad.com/A.txt")!) 

    httpGet(request){ (data, error) -> Void in 

     if error != nil { 

      print(error) 

     } else { 

      let delimiter = "\t" // Read a tab-delimited text file 

      let lines:[String] = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] 

      var ar = [Double]() 

      for line in lines { 

       var values:[String] = [] 

       if line != "" { 

        values = line.componentsSeparatedByString(delimiter) 
        // Put the values into the tuple and add it to the items array 

        let str = (values[1])//CHOOSE THE COLUMN TO PRINT (0, 1, 2) 

        // Convert string to double 

        let db = NSNumberFormatter().numberFromString(str)?.doubleValue 

        ar.append(db!) 

       } 

      } 


      for nn in ar { 

       self.candies.append(Candy(name: String(format:"%.4f", nn))) 

      } 

     } 

    } 

} 
+0

Vielen Dank Oliver! – Saif

+0

Kein Problem :) wenn es funktioniert bitte markieren Sie es als die richtige Antwort für die nächste Person zu sehen. –

Verwandte Themen