Error making guard statement Swift - ios

Please consider following:
let isHaveSn = model.positions.contains {$0.assortment?.isSerialTrackable == true}
guard isHaveSn else {
return
}
isHaveSn product Bool, and so i check that Bool in guard and everything work. But i want to simplify this like that:
guard model.positions.contains {$0.assortment?.isSerialTrackable == true} else {
return
}
It produce several errors, some of them: expected expression or Consecutive statement should be separated by ;
But i just copy right side of:
let isHaveSn = model.positions.contains {$0.assortment?.isSerialTrackable == true}
Why my code not compile?

The correct syntax for that would be:
guard model.positions.contains(where: {$0.assortment?.isSerialTrackable == true}) else {
return
}
Actually there was a proposal in swift-evolution to enable trailing closures in guard statements that was rejected. You can read more about it here

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

Ambiguous reference to member '==' with realm filter

do {
let result = try Realm().objects(Pros.self)
print(result)
let filterResult = result.filter({ $0.category.filter({$0.type_cat == ""})})
print(filterResult)
}
catch {
print(error)
}
and its give me error as "Ambiguous reference to member '=='"
so what i missing to add
I found solution and its work perfectly for me
do {
let result = try Realm().objects(Pros.self)
print(result)
let predicate = NSPredicate(format: "SELF.type == %# AND SELF.status == 'valide' AND ANY category.type_sector = %# AND SELF.status == 'valide'", arrType[(selectedFromType?.row)!], arrTypeSector[(selectedFromSector?.row)!])
let arrFiltered = result.filter(predicate)
print(arrFiltered)
}
catch
{
print(error)
}
Based on Realm docs, filtering chapter, try to change your request like this:
let type = ""
let result = try Realm().objects(Pros.self).filter("category.type_cat == %#",type)
Realm().objects(Pros.self) will return Result<Pros> which kind of Realm Data. Your filter function syntax is a function of Swift, doesn't of Realm. You should convert Result<Pros> to [Pros] before using filter like this:
let result = Array(try Realm().objects(Pros.self))
let filterResult = result.filter({ $0.category.filter({$0.type_cat == ""})})
Or you can using filter function build in Realm. Please check realm.io docs.

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.

Guard operation Swift 2

I use Swift 2 and Xcode 7.
I would like to know the difference between
if condition { ... } else { ... }
and
guard ... else ...
The really big difference is when you are doing an optional binding:
if let x = xOptional {
if let y = yOptional {
// ... and now x and y are in scope, _nested_
}
}
Contrast this:
guard let x = xOptional else {return}
guard let y = yOptional else {return}
// ... and now x and y are in scope _at top level_
For this reason, I often have a succession of multiple guard statements before I get to the meat of the routine.
Like an if statement, guard executes statements based on a Boolean value of an expression. Unlike an if statement, guard statements only run if the conditions are not met. You can think of guard more like an Assert, but rather than crashing, you can gracefully exit.
Reference and code example here.
To add to Matt's answer, you can include several conditions in a single guard statement:
guard let x = xOptional, y = yOptional else { return }
// ... and now x and y are in scope _at top level_
In addition to optional binding, a guard condition can test boolean results:
guard x > 0 else { return }
In short, the benefit of the guard statement is to make the early exit apparent at the start of the scope, instead of the condition being buried further down in a nested else statement.

Swift switch statement for matching substrings of a String

Im trying to ask for some values from a variable.
The variable is going to have the description of the weather and i want to ask for specific words in order to show different images (like a sun, rain or so)
The thing is i have code like this:
if self.descriptionWeather.description.rangeOfString("Clear") != nil
{
self.imageWeather.image = self.soleadoImage
}
if self.descriptionWeather.description.rangeOfString("rain") != nil
{
self.imageWeather.image = self.soleadoImage
}
if self.descriptionWeather.description.rangeOfString("broken clouds") != nil
{
self.imageWeather.image = self.nubladoImage
}
Because when i tried to add an "OR" condition xcode gives me some weird errors.
Is it possible to do a swich sentence with that? Or anyone knows how to do add an OR condition to the if clause?
I had a similar problem today and realized this question hasn't been updated since Swift 1! Here's how I solved it in Swift 4:
switch self.descriptionWeather.description {
case let str where str.contains("Clear"):
print("clear")
case let str where str.contains("rain"):
print("rain")
case let str where str.contains("broken clouds"):
print("broken clouds")
default:
break
}
Swift 5 Solution
func weatherImage(for identifier: String) -> UIImage? {
switch identifier {
case _ where identifier.contains("Clear"),
_ where identifier.contains("rain"):
return self.soleadoImage
case _ where identifier.contains("broken clouds"):
return self.nubladoImage
default: return nil
}
}
You can do this with a switch statement using value binding and a where clause. But convert the string to lowercase first!
var desc = "Going to be clear and bright tomorrow"
switch desc.lowercaseString as NSString {
case let x where x.rangeOfString("clear").length != 0:
println("clear")
case let x where x.rangeOfString("cloudy").length != 0:
println("cloudy")
default:
println("no match")
}
// prints "clear"
Swift language has two kinds of OR operators - the bitwise ones | (single vertical line), and the logical ones || (double vertical line). In this situation you need a logical OR:
if self.descriptionWeather.description.rangeOfString("Clear") != nil || self.descriptionWeather.description.rangeOfString("clear") != nil {
self.imageWeather.image = self.soleadoImage
}
Unlike Objective-C where you could get away with a bitwise OR in exchange for getting a slightly different run-time semantic, Swift requires a logical OR in the expression above.
If you do this a lot, you can implement a custom ~= operator that defines sub-string matching. It lends itself to this nice syntax:
switch "abcdefghi".substrings {
case "def": // calls `"def" ~= "abcdefghi".substrings`
print("Found substring: def")
case "some other potential substring":
print("Found \"some other potential substring\"")
default: print("No substring matches found")
}
Implementation:
import Foundation
public struct SubstringMatchSource {
private let wrapped: String
public init(wrapping wrapped: String) {
self.wrapped = wrapped
}
public func contains(_ substring: String) -> Bool {
return self.wrapped.contains(substring)
}
public static func ~= (substring: String, source: SubstringMatchSource) -> Bool {
return source.contains(substring)
}
}
extension String {
var substrings: SubstringMatchSource {
return SubstringMatchSource(wrapping: self)
}
}
I'd recommend using a dictionary instead, as a mapping between the substring you're searching for and the corresponding image:
func image(for weatherString: String) -> UIImage? {
let imageMapping = [
"Clear": self.soleadoImage,
"rain": self.soleadoImage,
"broken clouds": self.nubladoImage]
return imageMapping.first { weatherString.contains($0.key) }?.value
}
A dictionary gives you flexibility, adding new mappings is easy to do.
This link also describes overloading operator ~= which is actually used by the switch statement for matching cases to allow you to match regular expressions.

Resources