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 })
Related
I am trying to create a course avg calculator with textfields. However if I only want to enter in a few marks (i.e. not filling out all the textfields) I get a crash.
I get this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
In my code, I tried to avoid this nil value, but I get the error on that first line if I leave the first textfield blank. I do further calculations with these textfields, so I'm not sure if I will get similar errors once I fix these lines.
if b?.text != nil {
b?.text = String(Double(b!.text!)!/100)
}
if d?.text != nil {
d?.text = String(Double(d!.text!)!/100)
}
if f?.text != nil {
f?.text = String(Double(f!.text!)!/100)
}
if h?.text != nil {
h?.text = String(Double(h!.text!)!/100)
}
Force unwrap the double conversion
Double(b!.text!)!
is the reason as empty string can't be converted to double so it returns nil and as you use ! , hence the crash , you need
if let tex = b , content = tex.text , value = Double(content) {
print(value)
}
Also don't make the b var an optional make it !
var b:UITextField! // and make sure you init it
Edit: Don't create other vars to hold instance ones use them directly
#IBOutlet weak var weight1: UITextField!
if let content = weight1.text , value = Double(content) {
print(value)
weight1.text = "\(value/100)"
}
Double(b!.text!)!
This is the reason, your input text (b!.text!) is not convertible to double hence ended up with nil.
for ex: you might be giving input "12Th45", this is not convertible to double.
Always use optional binding wherever you are not sure that value is there or not.
Thanks.
This question already has answers here:
Check if optional array is empty
(8 answers)
Closed 4 years ago.
I have a array of my custom model, and I want to check if it is not nil and its size is greater then 0.
Following is my array with custom object
var listCountries : [Countries]? = nil
now In viewDIdLoad I want to make a check on it. I am new to Swift. I have good experience in working in Java.
I have read out Optional values concept and guard, if let statements. But I am unable to understand how efficiently they may be used. I have read too much SO questions but failed to figure out.
for example , if I want to check the upper given array in java I have only to do
if(listCountries != null && listCountries.size()>0){
//DO something
}
So to summarize my question:
How to make the upper given(Java code) check in to swift 4.? What is more smooth and reliable way.
What is a use of if let , guard, guard let statements. if I declare a variable (array, string) as optional I have to bear optional check like force wrapping each and every place. This is for me so making too much confusion.
Please help. I know this question has been asked in different ways. But this has some different context.
Just use ??.
if !(listCountries ?? []).isEmpty {
However, since you want to probably use listCountries in the if block, you should unwrap
if let listCountries = self.listCountries, !listCountries.isEmpty {
Ideally, if nil and empty means the same to you, don't even use an optional:
var listCountries: [Countries] = []
I would do it something like...
if let list = listCountries, !list.isEmpty { // Can also use list.count > 0
// do something
}
Even though you are not using the list inside the braces you are still using the list in the condition.
Or, like Sulthan said... make it non-optional to begin with if it makes no difference.
Obviously, I would assume that you are able to recognize the difference between nil array and empty array.
So, if we tried to implement a literal translation to your question:
I want to check if it is not nil and its size is greater then 0
For the first condition:
// "I want to check if it is not nil":
if let unwrappedList = listCountries {
// ...
}
and for the second condition:
// "I want to check if it is not nil":
if let unwrappedList = listCountries {
// "and its size is greater then 0":
if !unwrappedList.isEmpty {
// ...
}
}
However, you could combine both of the conditions by using the comma to achieve the multi-clause condition:
// I want to check if it is not nil and its size is greater then 0
if let unwrappedList = listCountries, !unwrappedList.isEmpty {
// ...
}
Or by using guard statement:
// I want to check if it is not nil and its size is greater then 0
guard let unwrappedList = listCountries, !unwrappedList.isEmpty else {
return
}
if let list = listCountries {
if(!list.isEmpty && list.count > 0) {
//value
}
}
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"]!)
Here's my code:
var goBack: String!
if (goBack == "yes")
{
firstName.text = passFirstName1
lastName.text = passLastName1
}
All I want to do is execute the if-statement if 'goBack' is undefined. How can I do that? (I don't know what to put in the blank)
The overall program is more complicated which is why I need the variable to be undefined at first. In short, I'm declaring 'goBack', asking the user to type in their first and last name, then continuing to the next view controller. That view controller has a back button that brings us back to the first view controller (where I declared 'goBack'). When the back button is pressed, a 'goBack' string is also passed of "yes". I also passed the first and last name to the next view controller but now I want to pass it back. I'm able to pass it back, its just a matter of making the text appear.
EDIT: firstName and lastName are labels while passFirstName1 and passLastName1 are variables from the second view controller.
"All I want to do is execute the if-statement if 'goBack' is undefined. How can I do that?"
To check whether a variable equals nil you can use a pretty cool feature of Swift called an if-let statement:
if let goBackConst = goBack {
firstName.text = passFirstName1
lastName.text = passLastName1
}
It's essentially the logical equivalent of "Can we store goBack as a non-optional constant, i.e. can we "let" a constant = goBack? If so, perform the following action."
It's really interesting, you can define a variable as optional, which means it may or may not be defined, consider the following scenerio:
you want to find out if the app has been installed before...
let defaults = NSUserDefaults()
let testInstalled : String? = defaults.stringForKey("hasApplicationLaunchedBefore")
if defined(testInstalled) {
NSLog("app installed already")
NSLog("testAlreadyInstalled: \(testInstalled)")
defaults.removeObjectForKey("hasApplicationLaunchedBefore")
} else {
NSLog("no app")
defaults.setValue("true", forKey: "hasApplicationLaunchedBefore")
}
Then all you need to do is write a function to test for nil...
func defined(str : String?) -> Bool {
return str != nil
}
And you've got it. A simpler example might be the following:
if let test : String? = defaults.stringForKey("key") != nil {
// test is defined
} else {
// test is undefined
}
The exclamation mark at the end is to for unwrapping the optional, not to define the variable as optional or not
"All I want to do is execute the if-statement if 'goBack' is undefined"
The guard statement (new in Swift 2) allows exactly this. If goBack is nil then the else block runs and exits the method. If goBack is not nil then localGoBack is available to use following the guard statement.
var goBack:String?
func methodUsingGuard() {
guard let localGoBack = goBack else {
print("goBack is nil")
return
}
print("goBack has a value of \(localGoBack)")
}
methodUsingGuard()
From The Swift Programming Language (Swift 3.1):
Constants and variables created with optional binding in an if
statement are available only within the body of the if statement. In
contrast, the constants and variables created with a guard statement
are available in the lines of code that follow the guard statement, as
described in Early Exit.
I'm using a label to display the string result of function. However I have a class variable that stores the previous result and I need to update that variable in different ways depending on different conditions. The code I wrote is
if(displayPassword.text == #"Memorable")
{
prevpass = [newPassword returnPassword];
}
else
{
prevpass = displayPassword.text;
}
However it always jumps to the else as it seems to show under debugging that displayPassword.text is always empty depsite it showing a value.
You can only use == to compare scalar values. A string is an object. You need to use the isEqual: or isEqualToString: method instead.
if([displayPassword.text isEqualToString:#"Memorable"]) {