Set label value dynamically in a table cell - ios

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"]!)

Related

How do I assert that a text field is empty?

I have an empty text field on my UI, though it has a placeholder text (whose value is foo) set in the storyboard. In my UI test, I am trying to check that its text value starts out empty, but when I query it's value, it seems to be giving me the placeholder value instead:
func testTextFieldInitiallyEmpty {
let input = XCUIApplication().textFields["My Text Field"]
XCTAssertEqual(input.value as! String, "")
}
as the test fails with this message:
XCTAssertEqual failed: ("foo") is not equal to ("")
Of course, foo is the placeholder value, but it's not the text value of that text field. I would have expected that error message if I had written:
XCTAssertEqual(input.placeholderValue as! String, "")
input is a XCUIElement, which implements XCUIElementAttributes, so I don't see anything else that would do the trick here.
How do I check (assert) that the text field is empty?
Edit
After doing some further research and trying out the suggestions below for using the input's properties of accessibilityValue, label, and title, I have not found any solution that will give me the text field's text value when there is text, and an empty string when only the placeholder is visible.
This seems like either (a) a bug, or (b) a questionable design decision from the test framework to not provide that ability. At a minimum, the documentation for XCUIElementAttributes#value seems inadequate to me, as the only detail is:
The exact type of value varies based on the type of the element.
Still looking for a better solution...
You can compare to the XCUIElementAttributes's placeholderValue variable in addition to checking for a blank string
extension XCUIElement {
func noTextEntered() -> Bool {
return self.value as? String != "" && self.value as? String != placeholderValue
}
}
Then you can run XCAssert(input.noTextEntered(), "Unexpected text entered into field")
Just make sure your placeholder is not something a user would type in. This way you don't have to hardcode placeholder values to check against
Kind of ridiculous that this is actually the case it works and that it needs a workaround.
Anyway, my solution to get the value w/o the placeholder interfering, based on #Jason's answer.
extension XCUIElement {
var valueWithoutPlaceholder: String {
if let v = value as? String, v != placeholderValue {
return v
}
return ""
}
}
Be aware, if the input is actually the placeholder this would break!
Try using accessibilityValue property of input.
func testTextFieldInitiallyEmpty {
let input = XCUIApplication().textFields["My Text Field"]
XCTAssertEqual(input.accessibilityValue, "")
}
If you command+click the property, you can see the following..
/*
Returns a localized string that represents the value of the element, such as the value
of a slider or the text in a text field. Use only when the label of the element
differs from a value. For example: A volume slider has a label of "Volume", but a value of "60%".
default == nil
default on UIKit controls == values for appropriate controls
Setting the property will change the value that is returned to the accessibility client.
*/
public var accessibilityValue: String?

Check Textbox with an Array Variable SWIFT

I'm wanting to check when the keyboard is dismissed, is it possible to check using
if firstName.text?.lowercaseString.rangeOfString(CheckArrayOfText) != nil
to check against a array variable like
var CheckArrayOfText:Array = [Word, Paragraph, Sentence]
I already know how to check it against just a string of text but not aginst a variable of an array by using
if firstName.text?.lowercaseString.rangeOfString("STRING") != nil
If I understand correctly, you're trying to see if the textfield contains any of the elements of the array. In that case, try:
let firstNameText = firstName.text?.lowercaseString
let result = CheckArrayOfText.contains(where: { firstNameText.rangeOfString($0) != nil })

App crashed when getting string from Dictionary (swift)

I converted a JSON to Dictionary and got some String by
title = json?.objectForKey("Titel_Live") as! String
But some times app will be crashed. I cannot reproduce this problem, just get information from crash reports.
Could someone help me and tell why? Thanks
Error at line 163
Crash reports
title = json?.objectForKey(“Titel_live”) as! String
This line of code where you are doing force unwrapped (Don't force the cast using !) is the cause means if object with key Titel_live dot not find then should be crashed, better go with optional chaining or use gaurd but yes your Json does't contain any object with key Titel_live(may be spelling mistake or object is array so validate once).
//better go like this check if exist or not.
if let t = json?.objectForKey(“Titel_live”) {
title = t
}
You should not force the casting to String.
You can try :-
title = json?.objectForKey("Title_Live") as? String (if title is optional variable)
if title is not optional then use:
title = (json?.objectForKey("Title_Live") as? String ?? "")
Because objectForKey will return nil if no value is associated with that key and force casting nil to String fails and causes crash.

how to take string from returned plist array

When I am trying to take the value from a plist and append it to an array
nameArray.append(namesArray!.objectForKey("Item1")! as! String)
The target item is a string but it appears to be inside the plist array, can anyone explain how to get it out please?
The print of namesArray!.objectForKey("Item1")! followed by the error are shown below:
Cast the value of the "Item1" key as an array of Strings, then fetch the first object from the array (since it appears there's only one). And if you like the idea that your app should not crash everytime a value is nil, better use if let than force-unwrapping everything with !.
Example:
if let names = namesArray,
let items = names.objectForKey("Item1") as? [String],
let result = items.first {
nameArray.append(result)
}
Just take the first element of your array:
nameArray.append((namesArray!.objectForKey("Item1")! as! [String])[0])

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

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]

Resources