Getting the count of an optional array as a string, or nil
Just do this:
textLabel.text = array?.count.flatMap { String($0} }
flatMap
on an optional will return either nil (if the optional was nil) or the result of running the closure and passing the optional as the argument.
Edit to surface other possible answers from the comments —jrc
array.map { String($0.count) }
— Kurt Revis(array?.count).map { String($0) }
— Martin R.
Swift: optional array count
That looks like the simpler way.
The Objective-C code is shorter only because nil
is also a form of 0, being a C-based language.
Since swift is strongly typed you don't have such a shorthand. In this specific case it requires a little more effort, but in general it saves you most of the headaches caused by loose typing.
Concerning the specific case, is there a reason for making the array optional in the first place? You could just have an empty array. Something like this might work for you:
var myArray: Array<String> = []
func numberOfObjectsInMyArray() -> Int {
return myArray.count
}
(Source for this information)
Is Array's count property an optional?
The count is not optional but the array is. Therefore areasOfAStudy?.count is optional, because when areasOfAStudy is a nil count never gets called so it evalutes to nil.
var areasOfAStudy: [String]? = nil
//This evaluates to nil because areasOfAStudy is nil. The type of a is Int?
var a = areasOfAStudy?.count
print(type(of:a))
Swift check for nil in optional array
Your problem there is that you have declared your Array
type as optional instead of declaring its elements. You just need to change your array declaration to[Any?]
. Note that the use of Any
it is not useful in most situations. I've been coding in Swift for more than 5 years and I've never needed to declare an element type as Any
.
Optional in Swift, return count of array
Let's take this a step at a time.
self.jsonObj
may be nil
so you need to treat it as an Optional:
self.jsonObj?["R"]
This will either return 1) nil
if self.jsonObj
is nil
or if "R" is not a valid key or if the value associated with "R" is nil
2) an Optional wrapped object of some type. In other words, you have an Optional of some unknown type.
The next step is to find out if it is an NSArray
:
(self.jsonObj?["R"] as? NSArray)
This will return an Optional of type NSArray?
which could be nil
for the above reasons or nil
because the object in self.jsonObj
was some other object type.
So now that you have an Optional NSArray, unwrap it if you can and call count
:
(self.jsonObj?["R"] as? NSArray)?.count
This will call count if there is an NSArray
or return nil for the above reasons. In other words, now you have an Int?
Finally you can use the nil coalescing operator to return the value or zero if you have nil
at this point:
(self.jsonObj?["R"] as? NSArray)?.count ?? 0
Check if optional array is empty in Swift
You could unwrap the optional array and use that like this, also use the new Int.random(in:)
syntax for generating random Int
s:
if let unwrappedArray = quotearray,
!unwrappedArray.isEmpty {
let item = unwrappedArray[Int.random(in: 0..<unwrappedArray.count)]
}
Check if optional array is empty
Updated answer for Swift 3 and above:
Swift 3 has removed the ability to compare optionals with >
and <
, so some parts of the previous answer are no longer valid.
It is still possible to compare optionals with ==
, so the most straightforward way to check if an optional array contains values is:
if array?.isEmpty == false {
print("There are objects!")
}
Other ways it can be done:
if array?.count ?? 0 > 0 {
print("There are objects!")
}
if !(array?.isEmpty ?? true) {
print("There are objects!")
}
if array != nil && !array!.isEmpty {
print("There are objects!")
}
if array != nil && array!.count > 0 {
print("There are objects!")
}
if !(array ?? []).isEmpty {
print("There are objects!")
}
if (array ?? []).count > 0 {
print("There are objects!")
}
if let array = array, array.count > 0 {
print("There are objects!")
}
if let array = array, !array.isEmpty {
print("There are objects!")
}
If you want to do something when the array is nil
or is empty, you have at least 6 choices:
Option A:
if !(array?.isEmpty == false) {
print("There are no objects")
}
Option B:
if array == nil || array!.count == 0 {
print("There are no objects")
}
Option C:
if array == nil || array!.isEmpty {
print("There are no objects")
}
Option D:
if (array ?? []).isEmpty {
print("There are no objects")
}
Option E:
if array?.isEmpty ?? true {
print("There are no objects")
}
Option F:
if (array?.count ?? 0) == 0 {
print("There are no objects")
}
Option C exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil
.
Previous answer for Swift 2.x:
You can simply do:
if array?.count > 0 {
print("There are objects")
} else {
print("No objects")
}
As @Martin points out in the comments, it uses func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool
which means that the compiler wraps 0
as an Int?
so that the comparison can be made with the left hand side which is an Int?
because of the optional chaining call.
In a similar way, you could do:
if array?.isEmpty == false {
print("There are objects")
} else {
print("No objects")
}
Note: You have to explicitly compare with false
here for this to work.
If you want to do something when the array is nil
or is empty, you have at least 7 choices:
Option A:
if !(array?.count > 0) {
print("There are no objects")
}
Option B:
if !(array?.isEmpty == false) {
print("There are no objects")
}
Option C:
if array == nil || array!.count == 0 {
print("There are no objects")
}
Option D:
if array == nil || array!.isEmpty {
print("There are no objects")
}
Option E:
if (array ?? []).isEmpty {
print("There are no objects")
}
Option F:
if array?.isEmpty ?? true {
print("There are no objects")
}
Option G:
if (array?.count ?? 0) == 0 {
print("There are no objects")
}
Option D exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil
.
Checking if array is nil or not
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] = []
Related Topics
Tableview Accessories Don't Load Correctly
How to Call Swiftui Navigationlink Conditionally
Create a Weak Container in Swift That Accepts a Native Swift Protocol
What the Difference of Keys and Values in Dictionary of Swift
How to Integrate Mapbox Sdk with Swiftui
Swift: How to Invalidate a Timer If the Timer Starts from a Function
How to Filter Nsarray in Swift
Datefromstring() Returns Incorrect Date
Convert Swift Encodable Class Typed as Any to Dictionary
Switch Statement for Imported Ns_Options (Rawoptionsettype) in Swift
Accessing Struct from One Class to Another
Swift Access Array with Index Gives Following Error. Any Idea Why
Rotation Gesture Produces Undesired Rotation
Tube Physics Body Acting Like Scncylinder, But How to Make It Act Like Scntube
Secure Text .Echosbullets Not Working for Password Field
How to Run App in Simulator Xcode 6
After Getting Image from Uiimagepickercontroller, Uiimageview Rotates Image for iPhone 5