Check if an object is the last in the array [duplicate] - ios

This question already has answers here:
Cannot convert value of type 'Meme!' to expected argument type '#noescape (Meme) throws -> Bool'
(2 answers)
Closed 6 years ago.
I have an array of [myObject] called myArray and an myObject object.
I want to check if myObject is the last object in myArray.
What is the best way to do it?
I've tried:
if myObject == myArray.last!
but it gives me this error:
Binary operator '==' cannot be applied to two 'myObject' operands
Any idea?
Thanks!

Try this one may be work for you.
let ary = ["1","2","3"]
if ary[0].isEqual(ary.last!){
print("Is last object")
}else{
print("Is Not last object")
}
Your output should be:Is Not last object
let ary = ["1"]
if ary[0].isEqual(ary.last!){
print("Is last object")
}else{
print("Is Not last object")
}
Your output should be:Is last object

Related

Testing if array contains at least one object that has some property [duplicate]

This question already has answers here:
Shorthand to test if an object exists in an array for Swift?
(2 answers)
Closed 4 years ago.
I want to test if the given array contains at least one object that contains a specific 'string' in it. Is it useful and possible?
Try filter().
struct S { let string: String }
let array = [ S(string: "a"), S(string: "b") ]
let hasAtleastOneA = array.filter({ $0.string == "a" }).count > 0
something like this :
let array = ["a","b","c"]
if array.count > 0 {
for name in array {
if name.contains("a"){
print("YES")
}
}
}
You check do this way,
let filtered = data.filter({$0.contains("test")})
Reference Higher order functions in swift: Filter, Map, Reduce, flatmap

Checking for null value (not nil or NSnull) in swift always return nil? [duplicate]

This question already has answers here:
How is optional binding used in swift?
(9 answers)
Closed 6 years ago.
I am working on a project which uses both swift an objective c. The team member before me have written this code in objective C ,which I am not familiar with. There is problem that most of the part involving storing and retrieving value from Sqlite is in obj C. This has been done in a common class to avoid Code redemption. However if i use swift to retrieve value through that obj C file a problem occur. If there is no value in that specified row it return "null".
Update: Checked for optional binding as said by Antony Raphel
Even if i check for nil directly before converting to 'as? String' the same error persist. I came to know that there is no equivalent of "null" in swift. Is there any hack to the value is empty (null) in swift?
Just replace your
var prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
and use
guard let prevNotifCount = self.cmmn.getPreviousNotificationCount() else{
print("No previous notification value")
return
}
no need to check for nil, if it will fail , else block will be executed
if let prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
{
self.cmmn.saveInDatabase("19", phoneNumber: "0", otp: "0")
print(self.cmmn.getPreviousNotificationCount())
}
else
{
print("No previous notification value")
}
This is standard Swift approach called optional binding. You safely unwrap an optional and if it is not nil assign it to a local variable
Try by adding if let to check nil condition like this:-
if let NotifCount = self.cmmn,getPreviousNotificationCount() as? String
{
prevNotifCount = NotifCount
}
Please try this, Hope it helps!
Use if let statement.
if let preNotifCount = self.cmmn.getPreviousNotofication {
//business logic
}
Now business logic would only be executed if preNotifCount is not nil.

Swift: Determine if array contains array [duplicate]

This question already has answers here:
Why can't I check to see if my array of arrays contains a specific array?
(2 answers)
Closed 7 years ago.
Im trying to figure out how to check if array contains another array:
var grid: [[Int]]!
grid = []
grid.append([1,1])
if grid.contains([1,1]) {
}
but the line
if grid.contains([1,1]) {
throws the error:
Contextual type '#noescape ([Int]) throws -> Bool' cannot be used with
array literal
Swift arrays doesn't conform to Equatable by default. But you can still compare them in the predicate:
if (grid.contains { $0 == [1,1] } == true) {
}

Swift 1.2 Results to '?' must be followed by a call, member lookup, or subscript [duplicate]

This question already has answers here:
swift ? must be followed by a call, member lookup, or subscript
(3 answers)
Closed 7 years ago.
Updating to Swift 1.2 / Xcode 6.3 caused the following errors:
Could someone with understanding of changes that took place between 1.1 and 1.2 help out what's going on here? All help appreciated! Thanks for reading this far!
In Swift 1.2, it is illegal to follow a variable with ? to unwrap it. The ? is used in an optional chain and must then be followed by a method call, a member lookup (i.e. a property), or a subscript as the error message said.
In the comments you added:
If I remove the "?" the code complies ok but what happens when a node
doesn't have a name?
It is perfectly valid to compare a String? to a literal String value without unwrapping the variable first. If the optional is nil, then nil is not equal to any literal String so the if will simply fail.
Try the following in a Swift Playground:
var str: String? = nil
if str == "hello" {
println("it is hello")
} else {
println("not hello") // prints "not hello"
}
// Here we reassign str, but it is still a String?
str = "hello"
if str == "hello" {
println("it is hello") // prints "it is hello"
} else {
println("not hello")
}
So it is completely safe just just compare paintedNode.name to "paintedArea" and if the node doesn't have a name then paintedNode.name will be nil and the if will fail just as if it had a different name.

Cannot invoke '==' with argument [duplicate]

This question already has answers here:
Check if property is set in Core Data?
(2 answers)
Closed 8 years ago.
I changed my core data model by adding an attribute to an entity. I've done a lightweight migration, but when I run the app I get a nil for some for the added attribute and thus a crash. I simply want to check for a nil and exclude the attribute if it is nil so as to avoid the crash. I've tried to do this with an if statement, but I get the error in the title. How can I get around this?
if comments == nil {
cell.textLabel!.text! = "\(totalWorkTimeInHours) hours"
cell.detailTextLabel!.text! = "Date: \(dateString)"
} else {
cell.textLabel!.text! = "\(totalWorkTimeInHours) hours"
cell.detailTextLabel!.text! = "Date: \(dateString)\nComments: \(comments)"
}
"Comments" is a string from Core Data. I know the error has something to do with the fact that I can't compare a string with nil, but I'm not sure how else to do it.
Thanks for the help!
var comments: String? = nil
if let comments = comments {
println(comments)
} else {
println("empty")
}

Resources