Within my struct I have the following:
subscript(index: Int) -> FileSystemObject {
var i: Int = 0
for a in contents! {
if (i == index) {
return a
}
i++
}
}
Where,
var contents: FileSystemObject = [FileSystemObject]?
But when,
let it: FileSystemObject = FileSystemObject()
And I write:
return it.contents![index]
I receive the error
Cannot subscript a value of type [FileSystemObject]
What am I doing wrong here?
Additionally, note that:
Changing each of the objects with the value
FileSystemObject
To,
[FileSystemObject]
Does not help.
EDIT 1:
This is the entirety of the code:
MainWindowController.swift
class MainWindowController: NSWindowController, NSOutlineViewDataSource, NSOutlineViewDelegate {
#IBOutlet weak var sourceView: NSOutlineView!
static var fileManager: NSFileManager = NSFileManager.defaultManager()
static var fileSystem: FileSystemObject = FileSystemObject(path: "/", fs: fileManager)
var outlineSource: OutlinePrep = OutlinePrep(fs: fileSystem)
override func windowDidLoad() {
super.windowDidLoad()
sourceView.setDataSource(self)
sourceView.setDelegate(self)
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
guard let it = item as? OutlinePrep else {
return outlineSource.basePath
}
return it.data[index]
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
// return (item == nil) ? YES : ([item numberOfChildren] != -1);
print(item)
guard let it = item as? OutlinePrep else {
return false
}
for (var i: Int = 0; i < it.data.count; i++) {
guard let _ = it.data[i].contents else {
return false
}
}
return true
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
guard let it = item as? OutlinePrep else {
return outlineSource.data.count
}
var i: Int = 0
for a in it.data {
guard let _ = a.contents else {
continue
}
i++
}
return i
}
}
FileSystem.swift
struct FileSystemObject {
let basePath: String
let name: String
var isDir = ObjCBool(false)
var contents: [FileSystemObject]?
init(path: String, fs: NSFileManager) {
basePath = path
let root: [String]
fs.fileExistsAtPath(path, isDirectory: &isDir)
if (isDir.boolValue) {
do {
root = try fs.contentsOfDirectoryAtPath(path)
}
catch {
root = ["Error"]
}
contents = []
for r in root {
contents!.append(FileSystemObject(path: (path + (r as String) + "/"), fs: fs))
}
}
name = path
}
subscript(index: Int) -> FileSystemObject {
get {
let error: FileSystemObject = FileSystemObject(path: "", fs: NSFileManager.defaultManager())
guard let _ = contents else {
return error
}
var i: Int = 0
for a in contents! {
if (i == index) {
return a
}
i++
}
return error
}
set {
}
}
}
Outline.swift
struct OutlinePrep {
var data: [FileSystemObject]
let basePath: String
private var cell: Int = -1
init (fs: FileSystemObject) {
data = fs.contents!
basePath = fs.basePath
}
mutating func outlineDelegate() -> String {
cell++
return data[cell].name
}
func testFunc(data: [FileSystemObject]) {
for (var i: Int = 0; i < data.count; i++) {
guard let d = data[i].contents else {
print(data[i].name)
continue
}
testFunc(d)
}
}
}
EDIT 2:
To clarify, I am inquiring as to how I might resolve the error, as all other provided code works as intended.
The error message is misleading. The problem becomes more apparent
if you split
return it.data[index]
into two separate statements:
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
guard let it = item as? OutlinePrep else {
return outlineSource.basePath
}
let fso = it.data[index]
return fso // error: return expression of type 'FileSystemObject' does not conform to 'AnyObject'
}
The value of it.data[index] is a
FileSystemObject, which is a struct and therefore it
does not conform to AnyObject and cannot be the return value
of that method. If you want to return a FileSystemObject
then you have to define that as a class instead.
simplified ...
struct FileSystemObject {
var context: [FileSystemObject]?
init() {
context = []
// your init is called recursively, forever ...
let fso = FileSystemObject()
context?.append(fso)
}
}
let s = FileSystemObject()
Related
I have an issue where I am calling a function, it's appending an array, and then I get a random element from it, the problem is that is keeps getting wiped right after the function is called before I can use it, therefore, the random element request is causing a fatal error.
Utilities.getKnockKnockJokes {
self.previousKnockKnockJoke = self.currentKnockKnockJoke
print("currentKnockKnockJoke = \(self.currentKnockKnockJoke)")
self.currentKnockKnockJoke = KnockKnockJokes.knockKnockJokes.randomElement()!
print("newCurrentKnockKnockJoke = \(self.currentKnockKnockJoke)")
self.singleServeText.text = self.currentKnockKnockJoke
}
The function called is below:
static func getKnockKnockJokes(completion: #escaping () -> Void) {
let db = Firestore.firestore()
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .background).async {
print("countKnockKnockJokes = \(self.countKnockKnockJokes)")
if self.countKnockKnockJokes == 0 {
while self.countKnockKnockJokes == 0 {
if self.countKnockKnockJokes == 0 {
self.countKnockKnockJokes = 1
group.leave()
}else {
print("leaving")
group.leave()
}
}
}else {
print("skipped")
group.leave()
}
}
group.notify(queue: .main) {
db.collection("jokes").document("Knock Knock Jokes").addSnapshotListener { document, error in
//check for error
if error == nil {
//check if document exists
if document != nil && document!.exists {
if let JokeNum = document!.get("JokeNum") as? Int {
self.countKnockKnockJokes = JokeNum
UserDefaults.standard.setValue(JokeNum, forKey: "countKnockKnockJokes")
print("KnockKnockJokeNum = \(self.countKnockKnockJokes)")
}
var count = 1
print("count = \(count)/\(self.countKnockKnockJokes)")
print("countKnockKnockJoke = \(self.countKnockKnockJokes)")
//Utilities.knockKnockJokes.removeAll()
KnockKnockJokes.knockKnockJokes.removeAll()
for _ in 0...self.countKnockKnockJokes {
print("count = \(count)/\(self.countKnockKnockJokes)")
if let Joke = document!.get("\(count)") as? String {
print("KnockKnockJokeNum = \(self.countKnockKnockJokes)")
if Utilities.jokes.contains("\(Joke) - From Knock Knock Jokes") {}else {
print("Joke = \(Joke)")
Utilities.jokes.append("\(Joke) - From Knock Knock Jokes")
KnockKnockJokes.knockKnockJokes.append(Joke)
print("KnockKnockJokes = \(KnockKnockJokes.knockKnockJokes)")
UserDefaults.standard.set(KnockKnockJokes.knockKnockJokes, forKey: defaults.knockKnockJokes.rawValue)
Utilities.updateJokesDefaults()
}
print("countKnockKnockFinal = \(count)/\(self.countKnockKnockJokes)")
if count == self.countKnockKnockJokes {
completion()
}
count = count + 1
}
}
}
}
}
}
}
try this:
if count == self.countKnockKnockJokes {
completion()
return // <--- here
}
I fixed it, my remove all was running after all the appends.
I have my two objects (Obj1 & Obj2) defined as below:
class Obj1: NSObject {
var code : String
init(code: String) {
self.code = code
}
}
class Obj2: NSObject {
var codeObj : Obj1
var value : Double
init(primary: Currency, value: Double) {
self.primary = primary
self.value = value
}
}
I have an array of Obj2 and I'm trying to update the array [Obj2] in such a way that the array only contains Obj2 whose codeObj.code are equal. Will including the Equatable protocol help in this?
I have tried this:
let filteredArray = array1.filter( { (c1: Obj2) -> Bool in
return conversion2.contains(where: { (c2: Obj2) -> Bool in
return c1.codeObj.code == c2.codeObj.code;
})
}) + array2.filter( { (c2: Obj2) -> Bool in
return conversion1.contains(where: { (c1: Obj2) -> Bool in
return c1.codeObj.code == c2.codeObj.code;
})
})
IS there a way to simplify this?
The only way for me is adding equatable to the objects like this:
class Obj1: NSObject {
var code : String
init(code: String) {
self.code = code
}
static func ==(lhs: Obj1, rhs: Obj1) -> Bool {
return lhs.code == rhs.code
}
}
class Obj2: NSObject {
var codeObj : Obj1
var value : Double
init(obj: Obj1, value: Double) {
self.codeObj = obj
self.value = value
}
static func ==(lhs: Obj2, rhs: Obj2) -> Bool {
return lhs.codeObj == rhs.codeObj
}
}
And to filter for equals, use for example:
// Test objects
let obj1A = Obj1(code: "aaa")
let obj1B = Obj1(code: "aba")
let obj1C = Obj1(code: "aaa")
let obj1D = Obj1(code: "cca")
let obj1E = Obj1(code: "aba")
let obj1F = Obj1(code: "xca")
let obj2A = Obj2(obj: obj1A, value: 12.0)
let obj2B = Obj2(obj: obj1B, value: 12.0)
let obj2C = Obj2(obj: obj1C, value: 23.0)
let obj2D = Obj2(obj: obj1D, value: 46.0)
let obj2E = Obj2(obj: obj1E, value: 23.0)
let obj2F = Obj2(obj: obj1F, value: 4.0)
var array = [obj2A, obj2B, obj2C, obj2D, obj2E, obj2F]
var onlyEqual = [Obj2]()
for object in array {
let count = array.filter({ $0 == object }).count
if count > 1 {
onlyEqual.append(object)
}
}
Where onlyEqual contains:
aaa
aba
aaa
aba
I am upgrading my app from swift 2 to swift 3 and have a significant performance loss when building an array of custom objects. In swift 2 this took a few seconds while in swift 3 it takes around 30 seconds. I am using alamofire to return swiftyJSON, returning about 3000 rows of data. the alamofire return is quick, its looping through this json to build array of custom objects thats slow. These objects greatly simplify the code written when building table cells and passing data to new views.
Code:
class Customer {
var ID: String!
var sysName: String!
var address: String!
var contactID: String!
required init(_name:String?, _id: String?, _address:String?, _contactID:String?) {
//print(json)
if _id != nil {
self.ID = _id
}else{
self.ID = ""
}
if _name != nil {
self.sysName = _name
}else{
self.sysName = ""
}
if _address != nil {
self.address = _address
}else{
self.address = "No Address on File"
}
if _contactID != nil {
self.contactID = _contactID
}else{
self.contactID = ""
}
}
}
Alamofire.request(API.Router.customerList()).responseJSON() {
response in
print(response.request ?? "") // original URL request
print(response.response ?? "") // URL response
print(response.data ?? "") // server data
print(response.result) // result of response serialization
if let json = response.result.value {
print("JSON: \(json)")
self.customers = JSON(json)
self.parseJSON()
}
}
func parseJSON(){
let jsonCount = self.customers["customers"].count
self.totalCustomers = jsonCount
for i in 0 ..< jsonCount {
self.loadedCustomers = i
print("customer = \(self.customers["customers"][i] ["sysName"].string!)")
//VERY SLOW
//create a customer object
let customer = Customer( _name: self.customers["customers"][i]["sysName"].string!, _id: self.customers["customers"][i]["ID"].string!, _address: self.customers["customers"][i]["mainAddr"].string!, _contactID: self.customers["customers"][i]["contactID"].string!)
//add customer to customer array
self.customersArray.append(customer)
}
self.layoutViews() //build view, call all table methods
}
Thanks
Improved code:
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
enum SearchMode{
case name
case address
}
class CustomerListViewController: ViewControllerWithMenu, UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating{
var indicator: SDevIndicator!
var totalCustomers:Int!
//data arrays
var ids = [String]()
var names = [String]()
var addresses = [String]()
var searchController:UISearchController!
var currentSearchMode = SearchMode.name
var customerTableView:TableView = TableView()
var layoutVars:LayoutVars = LayoutVars()
var sections : [(index: Int, length :Int, title: String)] = Array()
var customersSearchResults:[String] = []
var shouldShowSearchResults:Bool = false
let viewsConstraint_V:NSArray = []
let viewsConstraint_V2:NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Customer List"
view.backgroundColor = layoutVars.backgroundColor
getCustomerList()
}
func getCustomerList() {
//remove any added views (needed for table refresh
for view in self.view.subviews{
view.removeFromSuperview()
}
// Show Indicator
indicator = SDevIndicator.generate(self.view)!
Alamofire.request(API.Router.customerList()).responseJSON() {
response in
//print(response.request ?? "") // original URL request
//print(response.response ?? "") // URL response
//print(response.data ?? "") // server data
//print(response.result) // result of response serialization
do {
if let data = response.data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let customers = json["customers"] as? [[String: Any]] {
for customer in customers {
if let id = customer["ID"] as? String {
self.ids.append(id)
}
if let name = customer["sysName"] as? String {
self.names.append(name)
}
if let address = customer["mainAddr"] as? String {
self.addresses.append(address)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
// build sections based on first letter(json is already sorted alphabetically)
var index = 0;
var firstCharacterArray:[String] = [" "]
for i in 0 ..< self.names.count {
let stringToTest = self.names[i].uppercased()
let firstCharacter = String(stringToTest[stringToTest.startIndex])
if(i == 0){
firstCharacterArray.append(firstCharacter)
}
if !firstCharacterArray.contains(firstCharacter) {
let title = firstCharacterArray[firstCharacterArray.count - 1]
firstCharacterArray.append(firstCharacter)
let newSection = (index: index, length: i - index, title: title)
self.sections.append(newSection)
index = i;
}
if(i == self.names.count - 1){
let title = firstCharacterArray[firstCharacterArray.count - 1]
let newSection = (index: index, length: i - index, title: title)
self.sections.append(newSection)
}
}
self.layoutViews()
}
}
func layoutViews(){
indicator.dismissIndicator()
searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.placeholder = "Search Customers"
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.titleView = searchController.searchBar
let items = ["Name","Address"]
let customSC = SegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
customSC.addTarget(self, action: #selector(self.changeSearchOptions(sender:)), for: .valueChanged)
self.view.addSubview(customSC)
self.customerTableView.delegate = self
self.customerTableView.dataSource = self
self.customerTableView.register(CustomerTableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.customerTableView)
//auto layout group
let viewsDictionary = [
"view2":customSC,
"view3":self.customerTableView
]as [String:AnyObject]
let sizeVals = ["fullWidth": layoutVars.fullWidth,"width": layoutVars.fullWidth - 30,"navBottom":layoutVars.navAndStatusBarHeight,"height": self.view.frame.size.height - 100] as [String:Any]
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view2(fullWidth)]", options: [], metrics: sizeVals, views: viewsDictionary))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view3(fullWidth)]", options: [], metrics: sizeVals, views: viewsDictionary))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-navBottom-[view2(40)][view3(height)]", options: [], metrics: sizeVals, views: viewsDictionary))
}
/////////////// Search Methods ///////////////////////
func changeSearchOptions(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
currentSearchMode = .name
break
case 1:
currentSearchMode = .address
break
default:
currentSearchMode = .name
break
}
filterSearchResults()
}
func updateSearchResults(for searchController: UISearchController) {
filterSearchResults()
}
func filterSearchResults(){
customersSearchResults = []
switch currentSearchMode {
case .name:
self.customersSearchResults = self.names.filter({( aCustomer: String ) -> Bool in
return (aCustomer.lowercased().range(of: self.searchController.searchBar.text!.lowercased()) != nil) })
break
case .address:
self.customersSearchResults = self.addresses.filter({( aCustomer: String) -> Bool in
return (aCustomer.lowercased().range(of: self.searchController.searchBar.text!.lowercased()) != nil)
})
break
}
self.customerTableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
//print("searchBarTextDidBeginEditing")
shouldShowSearchResults = true
self.customerTableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = false
self.customerTableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if !shouldShowSearchResults {
shouldShowSearchResults = true
self.customerTableView.reloadData()
}
searchController.searchBar.resignFirstResponder()
}
/////////////// TableView Delegate Methods ///////////////////////
func numberOfSections(in tableView: UITableView) -> Int {
if shouldShowSearchResults{
return 1
}else{
return sections.count
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//print("titleForHeaderInSection")
if shouldShowSearchResults{
return nil
}else{
if(sections[section].title == "#"){
return " # \(self.totalCustomers) Customers Found"
}else{
return " " + sections[section].title //hack way of indenting section text
}
}
}
func sectionIndexTitles(for tableView: UITableView) -> [String]?{
print("sectionIndexTitlesForTableView 1")
if shouldShowSearchResults{
return nil
}else{
//print("sectionIndexTitlesForTableView \(sections.map { $0.title })")
return sections.map { $0.title }
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//print("heightForHeaderInSection")
if shouldShowSearchResults{
return 0
}else{
return 50
}
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return index
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print("numberOfRowsInSection")
if shouldShowSearchResults{
return self.customersSearchResults.count
} else {
return sections[section].length
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = customerTableView.dequeueReusableCell(withIdentifier: "cell") as! CustomerTableViewCell
customerTableView.rowHeight = 50.0
if shouldShowSearchResults{
let searchString = self.searchController.searchBar.text!.lowercased()
if(currentSearchMode == .name){
cell.nameLbl.text = self.customersSearchResults[indexPath.row]
cell.name = self.customersSearchResults[indexPath.row]
if let i = self.names.index(of: cell.nameLbl.text!) {
//print("\(cell.nameLbl.text!) is at index \(i)")
cell.addressLbl.text = self.addresses[i]
cell.address = self.addresses[i]
cell.id = self.ids[i]
} else {
cell.addressLbl.text = ""
cell.address = ""
cell.id = ""
}
//text highlighting
let baseString:NSString = cell.name as NSString
let highlightedText = NSMutableAttributedString(string: cell.name)
var error: NSError?
let regex: NSRegularExpression?
do {
regex = try NSRegularExpression(pattern: searchString, options: .caseInsensitive)
} catch let error1 as NSError {
error = error1
regex = nil
}
if let regexError = error {
print("Oh no! \(regexError)")
} else {
for match in (regex?.matches(in: baseString as String, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: baseString.length)))! as [NSTextCheckingResult] {
highlightedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: match.range)
}
}
cell.nameLbl.attributedText = highlightedText
}else{//address search mode
cell.addressLbl.text = self.customersSearchResults[indexPath.row]
cell.address = self.customersSearchResults[indexPath.row]
if let i = self.addresses.index(of: cell.addressLbl.text!) {
cell.nameLbl.text = self.names[i]
cell.name = self.names[i]
cell.id = self.ids[i]
} else {
cell.nameLbl.text = ""
cell.name = ""
cell.id = ""
}
//text highlighting
let baseString:NSString = cell.address as NSString
let highlightedText = NSMutableAttributedString(string: cell.address)
var error: NSError?
let regex: NSRegularExpression?
do {
regex = try NSRegularExpression(pattern: searchString, options: .caseInsensitive)
} catch let error1 as NSError {
error = error1
regex = nil
}
if let regexError = error {
print("Oh no! \(regexError)")
} else {
for match in (regex?.matches(in: baseString as String, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: baseString.length)))! as [NSTextCheckingResult] {
highlightedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: match.range)
}
}
cell.addressLbl.attributedText = highlightedText
}
} else {
//print("make cell")
cell.id = self.ids[sections[indexPath.section].index + indexPath.row]
cell.name = self.names[sections[indexPath.section].index + indexPath.row]
cell.address = self.addresses[sections[indexPath.section].index + indexPath.row]
cell.nameLbl.text = self.names[sections[indexPath.section].index + indexPath.row]
cell.addressLbl.text = self.addresses[sections[indexPath.section].index + indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRow(at: indexPath!) as! CustomerTableViewCell
let customerViewController = CustomerViewController(_customerID: currentCell.id)
navigationController?.pushViewController(customerViewController, animated: false )
tableView.deselectRow(at: indexPath!, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have a object like below which is an array of objects.
In swift language, How can i check whether object is an array of objects ?
DefinitionList = (
{
accountNum = {
isEditable = 1;
isRequired = 1;
};
bAccountType = {
isEditable = 1;
isRequired = 0;
},
},
{
accountNum = {
isEditable = 1;
isRequired = 1;
};
bAccountType = {
isEditable = 1;
isRequired = 0;
};
},
..
..)
Usually i use this in Swift 2 :
var DefinitionList = NSObject?()
DefinitionList = ["ciao" : "ciao"]
// DefinitionList = ["ciao"]
guard DefinitionList != nil else {
print("DefinitionList empty")
return
}
guard ((DefinitionList as? Array<NSObject>) != nil) else {
print("I'm a Dictionary")
return
}
print("I'm a Array")
Swift 3
var DefinitionList : NSObject?
// DefinitionList = ["ciao" : "ciao"] as NSObject
DefinitionList = ["ciao"] as NSObject
guard DefinitionList != nil else {
print("DefinitionList empty")
return
}
guard ((DefinitionList as? Array<NSObject>) != nil) else {
print("I'm a Dictionary")
return
}
print("I'm a Array")
You can use "is" operator in Swift language.
if objects is [AnyObject] {
print("right, its array of objects!")
} else {
print("no, its not an array of objects!")
}
Hope this will help you
I am trying to append data to an Array and save using TMCache, but it's like I'm doing it wrong. Cause, the data isn't being appended. I keep getting empty array
private var teams: Array<Teams> = Array<Teams>()
private var teamResults: [TeamResult]! {
didSet {
if teamResults.count <= 0 {
return
} else {
self.teams = []
for var index = 0; index < teamResults.count; index++ {
//print(index)
let categoryResult = teamResults[index]
if let categoryBackgroundImage = categoryResult["image"] as? PFFile {
categoryBackgroundImage.getDataInBackgroundWithBlock({ (data, error) -> Void in
if let dataGot = data {
let image = UIImage(data: dataGot)
let appendData = Teams(playing: categoryResult["playing"] as! Bool,
name: categoryResult["name"] as! String,
position: categoryResult["position"] as! Int,
image: image!)
//print(appendData.position)
self.teams.append(appendData)
}
print(self.teams.count) <-- I get 0
})
print(self.teams.count) <-- I get 0
}
}
TMCache.sharedCache().setObject(self.teams, forKey: "Teams")
self.mainTableView.reloadData()
for categ in teams {
print(categ.position)
}
}
}
}
getDataInBackgroundWithBlock works asynchronously. The data is returned later in the block.
You have to put the code to reload the table view into the block and check if the loop is finished.
For example (untested)
private var teams: Array<Teams> = Array<Teams>()
private var teamResults: [TeamResult]! {
didSet {
if teamResults.count <= 0 {
return
} else {
self.teams = []
var index : Int
for index = 0; index < teamResults.count; index++ {
//print(index)
let categoryResult = teamResults[index]
if let categoryBackgroundImage = categoryResult["image"] as? PFFile {
categoryBackgroundImage.getDataInBackgroundWithBlock({ (data, error) -> Void in
if let dataGot = data {
let image = UIImage(data: dataGot)
let appendData = Teams(playing: categoryResult["playing"] as! Bool,
name: categoryResult["name"] as! String,
position: categoryResult["position"] as! Int,
image: image!)
//print(appendData.position)
self.teams.append(appendData)
TMCache.sharedCache().setObject(self.category, forKey: "Teams")
if index == teamResults.count {
self.mainTableView.reloadData()
for categ in teams {
print(categ.position)
}
}
}
})
}
}
}
}
}