ios


Using map() to initialize array inline from array of Dictionary (i.e. a JSON array)


My class can be initialized from a JSON Dictionary
class ChildObject {
required init?(fromDictionary dictionary: [String:Any]) { //init... }
}
And now I was given an array of such Dictionaries:
// objectDictionaries = [[String:Any]]
Now I want to initialize an array of my class inline using map. I'm initializing an array inside another class.
class ParentObject {
var children: [ChildObject]
required init?(fromDictionary aDictionary: [String:Any]) {
guard let childDictionaries = aDictionary["children"] as? [[String:Any]],
let children = childDictionaries.map { ChildObject(fromDictionary: $0) }
else { return nil }
self.children = children
}
}
But this doesn't compile--- can anyone tell me the correct syntax? I tried forEach but that also didn't work.
In a playground I get
Expected else after guard
Anonymous closure argument not contained in a
closure
Expected Expression
Braces block of statements in an unused
closure
For both class you are having init? it means it will return nil to so when you map the array of dictionary it will give you result [ParentObject?] and [ParentObject?] it means array object are optional and you are trying to stored result in array of non-optional, To solved the problem simply use flatMap because it will ignored/reduce the nil and give you array of non-optional objects.
class ParentObject {
var children: [ChildObject]
required init?(fromDictionary aDictionary: [String:Any]) {
guard let childDictionaries = aDictionary["children"] as? [[String:Any]] else {
return nil
}
self.children = childDictionaries.flatMap { ChildObject.init }
}
}
Same goes for array of ParentObject
self.parents = objectDictionaries.flatMap { ParentObject.init }
Note: Return type of map is not the optional so remove it from the guard let like I have done.
map doesn't return an optional, so let children = childDictionaries.map { ChildObject(fromDictionary: $0) } can't be inside your guard clause.
On the other hand, ChildObject(fromDictionary: $0) does return an optional, something that map doesn't support.
You could use flatMap, so values that can't be initialized will be ignored:
class ParentObject {
let children: [ChildObject]
required init?(fromDictionary aDictionary: [String:Any]) {
guard let childDictionaries = aDictionary["children"] as? [[String:Any]],
else { return nil }
self.children = childDictionaries.flatMap { ChildObject(fromDictionary: $0) }
}
}
You can also return nil if all the children must be properly initialized:
required init?(fromDictionary aDictionary: [String:Any]) {
guard let childDictionaries = aDictionary["children"] as? [[String:Any]]
else { return nil }
let children = childDictionaries.flatMap { ChildObject(fromDictionary: $0) }
guard children.count == childDictionaries.count else { return nil }
self.children = children
}

Related Links

Bonjour network
Xamarin.iOS: NSTemporaryDirectory()
How to make an array from child nodes?
How to update a Pod in iOS App Swift
dyld: Library not loaded: #rpath/JSONModel.framework/JSONModel
How to implement airplay in an iOS app for streaming video on Apple TV
Touch ID Passcode Integration in iOS
how to get today's date less 18 years
iOS Not able to change the frame of UITextField inputAccessoryView.superview
Publishing issue, Callkit is included even we are not using it
How to get crash information from a TestFlight launched app?
Parse: Updating relation on user in Local Datastore
iOS 10, Local notification show when app is in forground?
What is the reason for this UITableView not showing up on my view controller?
Xcode inserted fileprivate functions after updating to Swift 3 [duplicate]
Xamarin ios UItableView Empty rows at top using Task Scheduler in background

Categories

HOME
demandware
elf
ssl-certificate
saml
twitter-digits
httpbuilder-ng
oracle-adf
apple-mail
base
hadoop2
hyperion
frequency
nservicebus
lighttpd
fbx
data-annotations
w2ui
thrift
swig
realm-java
dsc
wso2cep
code-signing
jtable
popupwindow
android-imageview
dapper-fastcrud
directx-12
skyscanner
panel-data
photo-gallery
gridstack
api-doc
data-science
ubuntu-server
json-rpc
solid-principles
signing
ulimit
gretl
dependency-management
singlepage
mysql-notifier
sizeof
hyperterm
oracle-policy-automation
rabbitvcs
highslide
thinktecture-ident-server
ospf
wchar-t
tun
perfview
fastparse
llvm-gcc
vraptor
mysql5
esx
culture
laravel-validation
epoll
android-menu
grunt-contrib-copy
sirtrevor
xcode6.1.1
modalpopupextender
dfsort
sshj
siblings
neventstore
guice-servlet
dynamic-usercontrols
eject
doophp
onmouseout
zmodem
magento-1.5
katta
android-assets
boost-gil
directoryentry
mkmapviewdelegate
arraycopy
webshop
drupal-gmap
anemic-domain-model
sqlprofileprovider

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App