Checking if text fields are empty cause error in Swift 2 - ios

I am trying to check if a textbox has no value.
When I do this:
if(userEmail?.isEmpty || userPassword?.isEmpty || userPasswordRepeat?.isEmpty)
I get the following error
I tried adding "?" before the ".isEmpty" but the error won't go away
Any ideas?

Try this....
if txtEmail.text?.isEmpty == true || txtPassword.text?.isEmpty == true || txtRePassword.text?.isEmpty == true{
print("true")
}

If interested also in positive case, the following is an alternative solution for Swift 2:
let email = self.txtEmail.text where !email.isEmpty, let password = self.txtPassword.text where !password.isEmpty {
//all fields are not nil && not empty
}else{
//some field is nil or empty
}

Related

How do I fix error: Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'

I am going through old code from HomeKit Catalog: Creating Homes, Pairing and Controlling Accessories, and Setting Up Triggers when I ran into an expression that says
.KeyPathExpressionType
I can't tell what the
.
in
.KeyPathExpressionType
is referring to on the left side of the
.
I find nothing when I search Google and stackoverflow for "KeyPathExpressionType". It's the same with
.ConstantValueExpressionType
I find nothing.
Each of those equality comparisons
comparison.leftExpression.expressionType == .KeyPathExpressionType
and
comparison.rightExpression.expressionType == .ConstantValueExpressionType
in the code below, generate an error message that says:
Binary operator '==' cannot be applied to operands of type 'NSExpression.ExpressionType' and '_'
extension NSPredicate {
/**
Parses the predicate and attempts to generate a characteristic-value `HomeKitConditionType`.
- returns: An optional characteristic-value tuple.
*/
private func characteristic() -> HomeKitConditionType? {
guard let predicate = self as? NSCompoundPredicate else { return nil }
guard let subpredicates = predicate.subpredicates as? [NSPredicate] else { return nil }
guard subpredicates.count == 2 else { return nil }
var characteristicPredicate: NSComparisonPredicate? = nil
var valuePredicate: NSComparisonPredicate? = nil
for subpredicate in subpredicates {
if let comparison = subpredicate as? NSComparisonPredicate, comparison.leftExpression.expressionType == .KeyPathExpressionType && comparison.rightExpression.expressionType == .ConstantValueExpressionType {
switch comparison.leftExpression.keyPath {
case HMCharacteristicKeyPath:
characteristicPredicate = comparison
case HMCharacteristicValueKeyPath:
valuePredicate = comparison
default:
break
}
}
}
if let characteristic = characteristicPredicate?.rightExpression.constantValue as? HMCharacteristic,
characteristicValue = valuePredicate?.rightExpression.constantValue as? NSCopying {
return .Characteristic(characteristic, characteristicValue)
}
return nil
}
I get the error to go away when I replace
comparison.leftExpression.expressionType == .KeyPathExpressionType
with
comparison.leftExpression.expressionType.rawValue == NSExpression.ExpressionType.keyPath.rawValue
and
comparison.rightExpression.expressionType == .ConstantValueExpressionType
with
comparison.rightExpression.expressionType.rawValue == NSExpression.ExpressionType.constantValue.rawValue
Is this correct? Can anyone tell me enlighten me on this problem?
The code is outdated Swift 2 code.
Replace .KeyPathExpressionType with .keyPath and .ConstantValueExpressionType with .constantValue
The type is NSExpression.ExpressionType, please read the documentation

Facing error as invalid literal for int () with base 10: in swift 2

As per screenshot while am submitting the feedback facing this issue. Any help is appreciated.
I have to enter comments like smile or sad after that am typing some text about the ride. Everything was working fine. While I am clicking on submit button I am getting journeyId as nil other than that in self.journeyAPIdetails I am getting the whole data from JSON. Thanks in advance.
func submitButtonTapped() {
if self.smileActive! == true || self.frownActive! == true {
let comment = (self.mainView.textfield.text! == "Tap to Type" || self.mainView.textfield.text! == "Leave any additional Comments here") ? "": self.mainView.textfield.text!
let rating = self.smileActive! == true ? "true":"false"
let journeyId = self.journeyAPIdetails!["data"]["journey_id"].stringValue
let userId = AccountService.sharedInstance.typeOfUser() == .Customer ? self.journeydetails?.driver.id : self.journeydetails?.customer.id
let details = ["rating":rating, "comment":comment, "journey_id":journeyId]
JourneyService().rateAUser(details).onSuccess { (json) -> Void in
if json["status"].stringValue == "success" {
print("dismissViewControllerAnimate")
self.dismissViewControllerAnimated(true, completion: nil)
AccountService.sharedInstance.clearJourneyContent()
} else if json["status"].stringValue == "fail" {
print("dismissViewControllerAnimated")
self.displayAlert("Error", message: json["message"].stringValue)
}
}
}
else {
super.displayAlert("Feedback", message: "Give some feedback and optionally add some comments.")
}
}
}
invalid literal for int () with base 10: '' is the error message from Python indicating you want to convert an empty string to an integer. This means the server expects a string that contains decimal digits, but you give it an empty string instead. This points to details having wrong input, in particular the journeyId field.
After discussing with OP, we find out the problem is in self.journeyAPIdetails!["data"]: it is an array containing an single object, but OP didn't notice it. So the solution is to change that line to:
let journeyId = self.journeyAPIdetails!["data"][0]["journey_id"].stringValue
// ^^^
Moral of the story: be careful to analyze the structure of the JSON you send and receive.

Swift optionals nil check

So I fail to figure a 1 liner for following syntax in Swift and it is driving me nuts:
if lastProfile == nil || lastProfile.id == profile.id {
useProfile(profile)
lastProfile = profile
}
Now see I could chain it but I'd still end up with 2-3 ifs. I could pack it out but then I again end up with 2-3 ifs... Is it possible to do this in just 1 swoop?
Edit:
My colleague found an alternative (although we agree ugly):
if !(latestProfile != nil && latestProfile!.voiceId != profile.voiceId) {
}
Is there a better approach than above?
Solution is just a ? away:
if lastProfile == nil || lastProfile?.id == profile.id {
print("true")
lastProfile = profile
}
This prints "true" when lastProfile is nil or when lastProfile and profile have the same id. Otherwise it prints nothing.
If lastProfile is declared as let lastProfile: Profile? = ..., and for example id is declared as optional also you can use it as:
if let lastProfileId = lastProfile?.id {
// lastProfile is not nil and id is not nil
}
else {
// lastProfile is nil or lastProfile.id is nil
}
It is called Optional Chaining and you can read about it on swift docs.
if let recentProfile = latestProfile where recentProfile.voieId != profile.voiceId {
useProfile(profile)
lastProfile = profile
}

Component separated by string crashing app swift

I have an app that converts textField input into an array of Int's by using componentSeparatedByString(",") but when i enter more than one comma in the textfield the app crashes, been trying to find a solution online but no luck, how can i fix this? I can keep it from crashing by checking for characters.first == "," ||characters.last == ",", but not consecutive commas.
enterValueLabel.text = ""
let circuits = circuitNumbersTextField.text!.componentsSeparatedByString(",")
let circuitNumbers = circuits.map { Int($0)!}
CircuitColors(circuitNumber: circuitNumbers, phaseColors: circuitPhaseColors )
if /*circuitNumbersTextField.text!.characters.first != "," || */circuitNumbersTextField.text!.characters.last != "," || (circuitNumbersTextField.text!.characters.first != "," && circuitNumbersTextField.text!.characters.last != ",")
Here's what I would do to make your code work. What is important here is the general idea, not the specific example I'm using (although it should work for you).
First, let's safely unwrap the text label:
if let text = circuitNumbersTextField.text {
}
Now that we avoid using circuitNumbersTextField.text! we know that an error wouldn't come from there.
Then we cut the sentence in components:
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
}
We use flatMap to safely unwrap the Optionals returned by Int():
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
let circuitNumbers = circuits.flatMap { Int($0) }
// circuitNumbers will only contain the successfully unwrapped values
}
Your code snippet:
if let text = circuitNumbersTextField.text {
let circuits = text.componentsSeparatedByString(",")
let circuitNumbers = circuits.flatMap { Int($0) }
if (circuits.first != "," && circuits.last != ",") || circuits.first != "," || circuits.last != "," {
// condition is met
} else {
// condition is not met
}
}
You can now safely use circuitNumbers in this code block without crashing.

Swift: Checking for the existence of a uitextfield

I have a controller that will have a variable number of textfields. On a button press I want to check for the existence of, whether or not its empty, and check the character count of the input.
I'm trying the following, which works fine if homePhone exists
if homePhone?.text != ""{
if countElements(homePhone1.text) != 10{
validInput = false
validationError = "Home Phone must be 10 digits"
}
}
But when a textfield does not exist (mobile) I get a fatal error
if mobilePhone?.text != ""{
if countElements(mobilePhone.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
fatal error: unexpectedly found nil while unwrapping an Optional value
Obviously I'm not doing the check correctly, optionals and unwrapping is continually tripping me up.
You can unwrap your textfield and check if it exists:
if let mobilePhoneField = mobilePhone{
if mobilePhoneField.text != ""{
if countElements(mobilePhoneField.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
}
This will check if your optional variable is nil or not so you can safely unwrap it, actualy it will do it for you.
if let value = myOptionalVariable{
//my optionalVariable is not nill i can do whatever i want
value.text = "Yaay"
}

Resources