'Binding' is not convertible to UILabel using SQLite in Swift - ios

My first time around here with a Swift related question with the SQLite.Swift library.
I have a for loop for a db.prepare statement, but I am stuck when trying to assign an array value to a UILabel.
// Prepare query to retrieve the message
var _phraseMessage:String = ""
let _stmt = _db.prepare("SELECT id, message FROM messages WHERE language = 'EN' AND category = 1 and username = 'user' LIMIT 1")
for row in _stmt {
println("id: \(row[0]), message: \(row[1])")
self._phraseMessageLabel = row[1] --> i get an error here **"'Binding' is not convertible to UILabel"**
}
How can assign the value in row[1] to my UILabel? Or even better to a String variable if possible.
Thanks in advance!
Disclaimer: This is my first attempt to Swift + Third party library

You're trying to set the UILabel property itself to your value - you want to set the text property on the label to your value:
self._phraseMessageLabel.text = row[1] as! String
If you want to assign the value to a variable:
var message = row[1] as! String
One thing to note is that with both approaches, your label text or variable will only end up being set to the value for the last row returned, the one that is processed last by the for loop.

Beyond Undo's fix above, I wanted to offer a couple other solutions.
Try using Database.scalar or Statement.scalar if you're only using a single value, as in your example above.
// make sure to remove "id" from your SELECT statement
self._phraseMessageLabel.text = _stmt.scalar() as! String
Note: Make sure to remove id from your SELECT statement; scalar returns the first column of the first row only.
Use the Statement.row cursor.
_stmt.step()
self._phraseMessageLabel.text = _stmt.row[1]

Related

How do I convert Collection of [UILabel] to string text to display on ViewController?

I am trying to display the same information on a collection of [UILabel], but I am getting this error,
Value of type '[UILabel]?' has no member 'text'
I am getting the specific error on this line in my code.
storagetypelabel.text = "\(booking.storageType.uppercased()) STORAGE"
Would love some input on how to alter the way my property.text label is typed.
Since I hooked up multiple UILabel to one [UILabel] collection, when I call the [UILabel] property, I should be able to display the same information for all the connected labels in the collection right?
text is a property of a single UILabel not an array , To set the text for all labels use
let str = "\(booking.storageType.uppercased()) STORAGE"
storagetypelabel.forEach { $0.text = str }

Set label value dynamically in a table cell

hello I am having a very weird problem in my code and I don't know whats actually going on here.
I have label set in my view controller and when I set the value like this
cell.totalTripsLabel.text = "55"
It works.
But If I try to set value from dictionary,
cell.totalTripsLabel.text = self.dict["totalTrips"]! as? String
It doesn't work at all and nothing displays on ViewController.
If I print the value like this
print(self.dict["totalTrips"]!)
It successfully prints the integer value
But If I do this
print(self.dict["totalTrips"]! as? String)
It prints nil
So I figure out by casting a value to string, it prints nil. So question is how I can set value in label which accepts string value
Dictionary result is like this
{
totalTrips = 2;
}
try this
cell.totalTripsLabel.text = String(self.dict["totalTrips"]!)

Multidimensional Array Looping in cellForRowAtIndexPath Swift

I have a multidimensional array that I want to display the values of onto one UILabel in each respective cell.
My arrays look like this:
var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]
I'm looping through these values in the cellForRowAtIndexPath in order for it to display on different cells (on a UILabel) the appropriate values:
if let onTheLabel: AnyObject = arrayOfContactsFound as? AnyObject {
for var i = 0; i < objects!.count; i++ {
cell?.contactsUserHas.text = "\(onTheLabel[indexPath.row][i])" as! String
print("arrayOfContactsFound Printing! \(onTheLabel)")
}
}
When printing to the console I get:
arrayOfContactsFound Printing! (
(
beverages,
"supply chain",
pharmacuticals
)
)
But on my label I get "beverages". That's it. How can I get the other 2 values (or X amount if there are more or less than 3 values)?
My for in loop is obviously not doing the trick. Assuming I can optimize/fix that to display all the values?
Thanks in advance.
In your loop you're setting the text of your label multiple times. Each time you set it it doesn't accumulate, it completely replaces the current text with the new text. You'll want something like this:
// Remove the cast and the loop in your code example, and replace with this
let items = arrayOfContactsFound[indexPath.row]
let itemsString = items.joinWithSeparator(" ")
cell?.contactsUserHas.text = itemsString
Another thing to note is your cast doesn't quite make a lot of sense.
var arrayExample = [["beverages", "food", "suppliers"]["other stuff, "medicine"]]
So arrayExample is of type [[String]]. I'm assuming each cell in your table view represents one of the arrays of strings in your array. So each cell represents one [String]. So your items should be arrayExample[indexPath.row]. The cast to AnyObject doesn't make too much sense. If anything you'd be casting it to [[AnyObject]], but there's no reason to because the compiler should already know it's [[String]].

SWIFT: var someVariable:int = textfield.text.toInt() x textfield2.text.toInt() and force unwrap

First post here so please be gentle. Am fairly new to coding and am trying to get my head around SWIFT and its optionals. Would really appreciate some advice from the pros!
I am writing a simple app whereby textfields are entered by the user and then some multiplication occurs in app before spitting out an answer into another textfield on the press of a button: "calculateTM".
I am having some trouble with the calculation itself and perhaps it's because I am trying to do too much on one line - take the textfield entry, convert to integer, multiply with another textfield entry converted to an integer, essentially what I wrote in the title:
var someVariable: Int = textfield.text.toInt() * textfield2.text.toInt()
The problem is, Xcode is wanting my to force unwrap and add an ! to the end of both toInt(). This is fine, except of course when the user doesn't enter anything into the boxes and presses calculate, at which point the nil value causes the program to crash, e.g.:
var someVariable: Int = textfield.text.toInt() x textfield2.text.toInt()
var someVariable2: Int = textfield3.text.toInt() x textfield4.text.toInt()
where the user doesn't enter anything into textfield3 or 4
Following this simple arithmetic, the code updates the labels (which are textfields) as such:
label1.text = String(someVariable)
label2.text = String(someVariable2)
So this final conversion back to a string might also create some issues as to how the optionals are treated in the first part of the code.
Apologies for the long-winded explanation, and I hope I've been clear enough, but I imagine I am missing something really basic with the first part of the code. I have tried using the optional ? and also the nil-coalescing operator (to set to 0 in case of nil) but can't get it to work. Please help?
Many thanks in advance!
Use if let for optional binding:
if let var1 = textField.text?.toInt(),
let var2 = textField2.text?.toInt() {
someVariable = var1 * var2 // or directly label1.text = String(var1 * var2)
}
The method toInt() actually returns an optional type 'Int?' that can be nil or integer value, so you need to check if the String->Int cast successful returns an Int or a nil.
For the most basic way:
var intValue: Int? = text.toInt()
if intValue != nil {
// operations using intValue!
}
In swift, you can try:
if let intValue = text.toInt() {
// operations
}

trying to populate a cell label with a string from an array

So, I have a cell with one label inside. I am trying to populate that label text with the various items in my array - all strings.
My array
var restauranttypelist: [String] = ["American", "Asian", "Bakery & Deli",
"Burgers", "Italian", "Mexican", "Seafood", "Steakhouse"]
and my cell label text
let type = restauranttypelist [indexPath.row]
var typecell = tableView.dequeueReusableCellWithIdentifier("cellone") as RestaurantTypeCell
typecell.restaurantTypeLabel.text = restauranttypelist.text
return typecell
I have tried a number of solution ranging from ".text" seen above, to ".String", to "restauranttypelist:indexPath.row" to no avail.
I suppose I have two questions. Am I setting up my array correctly? Do I need to insert the "[String]" portion after the variable name?
Finally, how would I be able to set the cell label to the numerous items I have in my array?
Thanks for any help... beginning.
Jon
In let type = restauranttypelist[indexPath.row] you're accessing a String from your Array and storing it in type. Therefore, all you need is typecell.restaurantTypeLabel.text = type.
There's nothing wrong with how you setup the array. You don't need the [String] type annotation since it can be inferred from the value you are assigning to it, but having it there does no harm.
Finally, this doesn't affect how your code works, but it's nice to know anyway:
Swift variable names follow the convention of starting with a lowercase character, and then capitalizing every subsequent word. Following that convention your variable names should be typeCell and restaurantTypeList.

Resources