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))
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
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.
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)]
}
Why are elements of Array in this case optional?
I'm pretty sure that the first element of this array is not nil
Yes but it's implementation doesn't know that , it's written also in case no values exist so optional comes to rescue
extension Array {
@inlinable public var first: Element? { get }
}
Function ArrayOptionalT - OptionalArrayT
Try this:
protocol OptionalType {
typealias W
var optional: W? { get }
}
extension Optional: OptionalType {
typealias W = Wrapped
var optional: W? { return self }
}
extension Array where Element: OptionalType {
func unwrap() -> [Element.W]? {
return reduce(Optional<[Element.W]>([])) { acc, e in
acc.flatMap { a in e.optional.map { a + [$0] } }
}
}
}
And then,
let a: [Int?] = [1, 2, 3]
let b: [Int?] = [1, nil, 3]
a.unwrap() // ==> [1, 2, 3]
b.unwrap() // ==> nil
Related Topics
Swift Ensembles Set Up & Ubiquitycontaineridentifier
Getting an Ip Address and Port Number from a Sockaddr_In Struct in Swift
Avoid Equatable and Hashable Boilerplate, Swift 4.2
Indent Second Line of UIlabel (Swift)
Swift Displaying The Time or Date Based on Timestamp
How to Show Two Row of Text in a Menu Bar App in MAC Os
Uirefreshcontrol Glitching in Combination with Custom Tableviewcell
Animate Line Under One Button to Another
Create Tab Bar Controller and Navigation Controller
Use The Same View for Adding and Editing Coredata Objects
Swift Spritekit Get Visible Frame Size
Add Custom .Colornames to UIcolor Somehow
How to Run Terminal Command in Swift from Any Directory
Place Multiple Scn Objects in Touchesbegan Method
How to Constrain Second Nsviewcontroller Minimum Size in Os X App