Use of undeclared type 'Player' - ios

I had an error in the variables player, I find fault has not been able to finish
import UIKit
class PlayersViewController: UITableViewController {
var players:[Player] = playersData
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerCell", forIndexPath: indexPath)
let player = players[indexPath.row] as Player
cell.textLabel?.text = player.name
cell.detailTextLabel?.text = player.game
return cell
}
}

You need to define the Player type first. You may think of something like this:
class PlayersViewController: UITableViewController {
var players: [Player] = []
var xplayers: [XPlayer] = []
// struct type of Player
struct Player {
var name : String = ""
var height : Int = 0
}
// OR
// tuple type of XPlayer
typealias XPlayer = (String, Int)
func someMethod() {
self.players.append(Player(name: "John Herbert", height: 160))
// OR
self.xplayers.append(("John Herbert", 160))
}
}

Related

How to get the name list on Realm database and display on my stimulator?

Here I have a Realm Database which is have some data in it and I want to display it on my Stimulator but it turn out display some other thing. What's wrong in my code?
This is the data of my Realm Database and I also marked the data which I want to display it.
The stimulator which display something like this.
And here is my ViewController.swift code's.
import UIKit
import RealmSwift
class ViewController: UIViewController,UITableViewDataSource { //UITableViewDataSource
#IBOutlet weak var mytableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
return theItem.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
print(theItem)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
//I suspect the problem is at here...
cell?.textLabel?.text = "\(theItem)"
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
class Category: Object {
#objc dynamic var name: String?
#objc dynamic var caid: Int = 0
}
class Item: Object {
#objc dynamic var name: String?
#objc dynamic var itemid: Int = 0
#objc dynamic var cateid: Int = 0
}
Your problem is that you need to get the string from the Item object. try something like
"\(theItem.name)".
func getNames() -> [String]{
let items = realm.objects(Item.self).filter("itemid >= 1").toArray(ofType: Item.self ) as [Item]
return items.map { $0.name }
}
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
I found a way to display the data already. I just need to add indexPath.row in my code and it can handle the data already.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let realm = try! Realm()
let theItem = realm.objects(Item.self).filter("itemid >= 1")
//I only add below this indexpath
let cellData = theItem[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
//and change this part and it's done.
cell?.textLabel?.text = cellData.name
print(theItem)
return cell!
}

Swift generic enums for as TableView data source

I want to create a UITableViewController that accepts an enum as it's data source.
The thing is, I have quite a few enums that I want it to be able to handle.
I created a protocol called TableViewSelectable and created some enums that conform to it like so:
protocol TableViewSelectable {
}
enum Genders: Int, TableViewSelectable {
case male = 0, female
static let allKeys = [male, female]
static let allNames = [male.getName, female.getName]
var getName: String {
switch self {
case .male:
return "Male"
case .female:
return "Female"
}
}
}
enum Goals: Int, TableViewSelectable {
case gainMuscleMass, getTrimFit, loseWeight
static let allKeys = [gainMuscleMass, getTrimFit, loseWeight]
static let allNames = [gainMuscleMass.getName, getTrimFit.getName, loseWeight.getName]
var getName: String {
switch self {
case .gainMuscleMass:
return "Gain muscle mass"
case .getTrimFit:
return "Get trim & fit"
case .loseWeight:
return "Lose weight"
}
}
}
And I have created an instance variable on my UITableViewController like so:
class ChoiceListTableViewController: UITableViewController {
var data: TableViewSelectable?
}
The problem is I have no idea how to go from here.
What I want to have is the option to give that UITableViewController any enum that conforms to TableViewSelectable in order to use as its data source.
I want to access it on the UITableViewController like this:
final class ChoiceListTableViewController: UITableViewController {
var data: TableViewSelectable?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
}
}
// MARK: Table View Data Source & Delegate
extension ChoiceListTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.allKeys.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChoiceTableViewCell", for: indexPath)
cell.textLabel?.text = data.allNames[indexPath.row]
return cell
}
}
Help please? :)
The issue with your current implementation is that the allKeys and allNames static properties that you should be using in your UITableViewDataSource method are not part of the TableViewSelectable protocol, so you cannot access them using the data variable.
You should modify your protocol to include these.
protocol TableViewSelectable {
static var allKeys: [TableViewSelectable] {get}
static var allNames: [String] {get}
}
You also need to modify your enums conforming to it accordingly.
enum Genders: Int, TableViewSelectable {
case male = 0, female
static let allKeys:[TableViewSelectable] = [male, female]
static let allNames = [male.getName, female.getName]
var getName: String {
switch self {
case .male:
return "Male"
case .female:
return "Female"
}
}
}
enum Goals: Int, TableViewSelectable {
case gainMuscleMass, getTrimFit, loseWeight
static let allKeys:[TableViewSelectable] = [gainMuscleMass, getTrimFit, loseWeight]
static let allNames = [gainMuscleMass.getName, getTrimFit.getName, loseWeight.getName]
var getName: String {
switch self {
case .gainMuscleMass:
return "Gain muscle mass"
case .getTrimFit:
return "Get trim & fit"
case .loseWeight:
return "Lose weight"
}
}
}
Then you can simply use data.allKeys and data.allNames to access the corresponding element of these arrays in your data source methods.
class ChoiceListTableViewController: UITableViewController {
var data:TableViewSelectable.Type! // make sure that this is actually initialized before accessing it
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.allKeys.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath)
cell.textLabel?.text = data.allNames[indexPath.row]
return cell
}
}

Group and sort Backendless data in UITableview with Swift

I'm looking to group and sort a list of users from backendless, similar to iPhone contacts. I want to add sectionIndexTitlesForTableView(_:), titleForHeaderInSection(_:), and sectionForSectionIndexTitle(_:). I haven't found a tutorial on how to do this, and I have been stuck for weeks.
So far, I'm able to retrieve users and populate the table view. I also implemented UISearchBarDelegate.
var users: [BackendlessUser] = []
var filteredUsers : [BackendlessUser] = []
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return users.count
} else {
return self.filteredUsers.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if tableView == self.tableView {
let user = users[indexPath.row]
cell.textLabel?.text = user.name
} else {
let filteredUser = filteredUsers[indexPath.row]
cell.textLabel?.text = filteredUser.name
}
return cell
}
You must have a dictionary of array (name 'data' for example)
data["A"] = ["Ananas", "Anaconda", "Apple"]
data["B"] = ["Banana", "Baby"]
...
data["Z"] = ["Zoro"]
begin:
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var headers: [String] = []
var data : [String: [String]] = [:] // Choose your type
override func viewDidLoad(){
// Do your stuff...
headers = letters.keys.sort()
// init your data var
data = ...
tableView.reloadData()
}
for header:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return headers.count
}
func sectionHeaderTitlesForTableView(tableView: UITableView) -> [String]?{
return headers
}
func tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return headers[section];
}
cell
func tableView(tableView: UITableView, numberOfRowInSection section: Int) -> Int {
// Exemple
return data[section].count
}

Pass data from struct array to new tableview controller

I am trying to pass data from my Cheats struct into a new tableviewcontroller to populate the new table with the relevant info.
I have done research but am new to swift.
I do have experience in php but transferring my knowledge is proving quite difficult...
In my prepare for segue class i receive a few errors:
Definition conflicts with previous value:
var DataPass = CheatsArray[indexPath.row]
Cannot assign value type 'String' to '[String]':
DestViewController.CheatsArray = DataPass.name
Here is a copy of my current 3 files
Structs and arrays:
struct Game {
var name : String
var cheats : [Cheat]
}
struct Cheat {
var name : String
var code : String
var description : String
}
// Create Our Game Info And Cheats / Codes For Each Game!
//-------------------------------------------------------
let COD4 = Game(name: "Call Of Duty 4", cheats: [Cheat(name: "Cheat", code: "Code", description: "Description")])
let GTAV = Game(name: "Grand Theft Auto 5", cheats: [Cheat(name: "Cheat", code: "Code", description: "Description")])
// Place Our New Games Inside This Array!
//---------------------------------------
let ArrayOfGames = [COD4,GTAV]
GameListController:
import Foundation
import UIKit
class GamesListViewController: UITableViewController {
var CheatsArray = [Game]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ArrayOfGames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = ArrayOfGames[indexPath.row].name
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
let DestViewController = segue.destinationViewController as! CheatsListViewController
let DataPass : Game
var DataPass = CheatsArray[indexPath.row]
DestViewController.CheatsArray = DataPass.name
}
}
CheatListController:
class CheatsListViewController: UITableViewController {
var CheatsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CheatsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)
cell.textLabel?.text = CheatsArray[indexPath.row]
return cell
}
}
The first error is because you defined DataPass twice, one row after another. You can't do that in the same scope. Change the name of one.
The second error is because you cannot assign value type 'String' to '[String]'. Just looking at CheatsArray and name variables, it's clear the first is an array and the second is most likely a string. You might want to append the name to the array.

TableView error: titleForHeaderInSection/Swift

I am working on a table view project I've seen in a tutorial, then I came across this piece of code that gives me the **error: Definition conflicts with previous value.**
The piece of code is:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int, titleForHeaderInSection section:Int) -> String? {
// Return the number of rows in the section.
return animalSelectionTitles[section]
}
I have tried to change the String? into String or Int, but String gives me the same error and Int gives me an error on the return line.
Here's my complete code:
import UIKit
class AnimalTableViewController: UITableViewController {
var animalsDict = [String: [String]] ()
var animalSelectionTitles = [String] ()
let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
func createAnimalDict() {
for animal in animals {
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
if var animalValues = animalsDict[animalKey] {
animalValues.append(animal)
animalsDict[animalKey] = animalValues
} else {
animalsDict[animalKey] = [animal]
}
}
animalSelectionTitles = [String] (animalsDict.keys)
animalSelectionTitles.sort({ $0 < $1})
animalSelectionTitles.sort( { (s1:String, s2:String) -> Bool in
return s1 < s2
})
}
override func viewDidLoad() {
super.viewDidLoad()
createAnimalDict()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return animalSelectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int, titleForHeaderInSection section:Int) -> String? {
// Return the number of rows in the section.
return animalSelectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = animals[indexPath.row]
// Convert the animal name to lower case and
// then replace all occurences of a space with an underscore
let imageFilename = animals[indexPath.row].lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "_", options: nil, range: nil)
cell.imageView?.image = UIImage(named: imageFilename)
return cell
}
Two things:
1)
You should change your line
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
Currently it substrings from the 2nd character, which means that for the input Black Swan then animalKey would be equal to lack Swan. Instead you should use the following line:
let animalKey = animal.substringToIndex(advance(animal.startIndex, 1))
2)
There is no method in the UITableViewDataSource Protocol which is called tableView:numberOfRowsInSection:titleForHeaderInSection. Instead you need to split it into the following two methods:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let title = animalSelectionTitles[section]
return animalsDict[title]!.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return animalSelectionTitles[section]
}
UPDATE 1:
In your tableView:cellForRowAtIndexPath, you should also update the retrieving of the animal name to reflect what is stored in the dictionary like so:
// Configure the cell...
let secTitle = animalSelectionTitles[indexPath.section]
let animalName = animalsDict[secTitle]![indexPath.row]
cell.textLabel?.text = animalName

Resources