Get only the string value from NSArray output - arrays

I am storing values from Json response like
self.NameArray = self.attachmentsArray.valueForKey("filename") as! NSArray
Output:
NameArray(("Din.pdf","img.jpeg"),(),(),("41_58"))
I got this output. I need to get the array only having ("Din.pdf","img.jpeg","41_58").
How to get it using swift code?

Convert NSArray to Swift Type [[String]]:
let NameArray:NSArray = [["Din.pdf","img.jpeg"], [], [], [ "41_58" ]]
let swiftArray = NameArray as! [[String]]
let flattenedArray = swiftArray.flatMap{ $0 }
Credits: Eric Aya and Flatten a Array of Arrays in Swift
If you do not want to convert it into Swift Type:
let NameArray:NSArray = [["Din.pdf","img.jpeg"], [], [], [ "41_58" ]]
let arrFiltered:NSMutableArray! = []
for arr in NameArray {
for a in arr as! NSArray {
arrFiltered.addObject(a)
}
}
print(arrFiltered)

Related

Cannot assign value of type '[String]' to type '[[String : Any]]'

Swift Xcode version 13.2.1
Here we have two Arrays,(1)var dicSearch=String and (2)var searchingDic: [[String: Any]]=[] I want to assign searchingDic to dicSearch when i implement it than it show error like, Cannot assign value of type '[String]' to type '[[String : Any]]'
here's my code, please anyone help!
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchingDic = dicSearch.filter{filtering in
let filterService = filtering["fName"] as? String
return((filterService?.lowercased().contains(searchText.lowercased()))!)
}
It looks like you are trying to create a filtered list based on a search term, but your dicSearch type is an array of strings (i.e: [String]), while your searchingDic is an array of dictionaries (i.e: [[String : Any]]).
This might be confusing when coming from a different language, but in Swift, the following declaration is a dictionary:
var dict: [String: Any] = [
"key1": "value1",
"key2": "value2",
]
so the following:
var arrayOfdicts: [[String: Any]] = [
["foo": "bar"],
["apples": "oranges"],
dict
]
is actually an array, containing a list of dictionaries, notice how I've put the dict declared above in the second array.
The compiler is telling you that you cannot assign a '[String]' to type '[[String : Any]]'
because this:
// example to an array of strings
var fullList: [String] = [
"apples",
"bananas",
"cucumbers"
]
// is not the same as
var arrayOfdicts: [[String: Any]] = [
["foo": "bar"],
["apples": "oranges"],
dict
]
The Array#filter method, iterates the array itself, and returns a new array with only the elements that return true in the return statement.
so either both your arrays need to be [String] or both your arrays need to be [[String:Any]]
example for String arrays:
// array
var fullList: [String] = [
"apples",
"bananas",
"cucumbers"
]
var filteredList: [String] = []
var searchTerm = "b"
filteredList = fullList.filter{ item in
let value = item
return value.lowercased().contains(searchTerm)
}
print(filteredList) // prints ["bananas", "cucumbers"]
an example for filtering with array of dictionaries:
var people: [[String: Any]] = [
["name": "Joe"],
["name": "Sam"],
["name": "Natalie"],
["name": "Eve"]
]
var filteredPeople: [[String: Any]] = []
var nameFilter = "a"
filteredPeople = people.filter{ item in
let value = item["name"] as! String
return value.lowercased().contains(nameFilter)
}
print(filteredPeople) // prints [["name": "Sam"], ["name": "Natalie"]]
Hope this helps :)

How to filter Dictionary of Array Swift3.0?

I've an Dictionary which contains Array and that Array has another Dictionary ant it also has another array. How do I get the last array by using 'Dictionary.Filter'.
For Example
Dict1->Array1->Dict2->Array2.
Here I need
Array2
I want to get "DeviceLsit" Array
Check this out! Based on your screenshot, I have managed to achieve it!
func filterArray() {
let dictPlist = Dictionary<String, Any>()
if let arrKeyName = dictPlist["key"] as? Array<Dictionary<String, Any>> {
let yourSecondArray = arrKeyName.filter({ (keyDict) -> Bool in
guard let _ = keyDict["keyName"] as? Array<Any> else {
return false
}
return true
})
}
}
Hope this helps!
if you want array of DeviceLists you can got through categories and get device lists
let root: [String: Any] = ["Categories": [ ["deviceList": ["1","2","3","4"]], ["deviceList": ["5","6","7","8"]] ]]
if let categories = root["Categories"] as? [Any] {
var deviceLists: [String] = []
for cat in categories {
if let cat = cat as? [String: Any], let deviceNames = cat["deviceList"] as? [String] {
deviceLists.append(contentsOf: deviceNames)
}
}
print(deviceLists)
}
here is the short anser :
Assume that your desired Array has Any Type. you can make it as you want like String , Int etc...!
let dict = [String:[[String:[Any]]]]()
let arr = dict.flatMap({($0.value).flatMap({($0.values)})}).last
print(arr) <-- your desired Array

Swift3 get element from array

I have a json string converted to string array like below:
let str = "{ \"dtResult\": [ { \"itmdtl_item_no\": \"AO406705959SE3\" }, { \"itmdtl_item_no\": \"AO406708959SE3\" } ] }"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
let item = result[0] as! [String:Any]
print(item)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
When i print out the result of item, i got the value like this:
["itmdtl_item_no": AO406705959SE3]
But i just want the string "AO406705959SE3", how can i do? Thanks.
First of all don't write
let result = json["dtResult"] as? [[String:Any]] ?? [ ]
If result is nil or empty the app will crash on result[0]
Instead write to check if the array exists and is not empty
if let result = json["dtResult"] as? [[String:Any]], !result.isEmpty {
let item = result[0] as! [String:Any]
// Now get the value for key "itmdtl_item_no"
if let itemNo = item["itmdtl_item_no"] as? String {
print(itemNo)
}
}

Convert Array<String> to String then back to Array<String>

say I have a variable
let stringArray = "[\"You\", \"Shall\", \"Not\", \"PASS!\"]"
// if I show this, it would look like this
print(stringArray)
["You", "Shall", "Not", "PASS!"]
now let's have an Array< String>
let array = ["You", "Shall", "Not", "PASS!"]
// if I convert this into string
// it would roughly be equal to the variable 'stringArray'
if String(array) == stringArray {
print("true")
} else {
print("false")
}
// output would be
true
now say what should I do to convert variable 'stringArray' to 'Array< String>'
The answer would be to convert the string using NSJSONSerialization
Thanks Vadian for that tip
let dataString = stringArray.dataUsingEncoding(NSUTF8StringEncoding)
let newArray = try! NSJSONSerialization.JSONObjectWithData(dataString!, options: []) as! Array<String>
for string in newArray {
print(string)
}
voila there you have it, it's now an array of strings
A small improvement for Swift 4.
Try this:
// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)
For other data types respectively:
// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

Swift NSUserDefaults setObject for Array

i need to save with NSUserDefaults an array that i get from jSON, the problem is it save only the first string and not all the array. So if the array is like NewYork,London,Rome .. it save only NewYork. I use it for a picker view.
This is the code:
EDIT
For save the Array from jSON:
if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? [String:AnyObject] { // dictionary
if let locationsArray = jsonData["locations"] as? [[String:AnyObject]] { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["location_name"] as? String { // finally, access the dictionary like you were trying to do
// println(location)
var locationSave: Void = save.setObject(location, forKey: "Location")
}
}
}
}
}
and for request the Array:
var Location = save.objectForKey("Location")!
var pickerviewFields = Location
return pickerviewFields.count
Thanks in advance!
You can only save an NSArray, if the Array is a Swift Array, you will need to convert it. Also, NSArray and NSDictionary objects, their contents must be property list objects.
Here's how you would convert the Array:
var MyArray = ["a", "b", "c"]
var MyNSArray: NSArray
MyNSArray = MyArray as NSArray
println("\(MyNSArray)")
Prints: (a,b,c)
I have a small example with some sample JSON:
var myJSONString: NSString = "{ \"locations\" : [ { \"location_name\" : \"A\" }, { \"location_name\" : \"B\" }, { \"location_name\" : \"C\" }, { \"location_name\" : \"D\" } ] }"
var urlData: NSData? = NSData()
var error: NSError?
var save = NSUserDefaults.standardUserDefaults()
urlData = myJSONString.dataUsingEncoding(NSUTF8StringEncoding)
if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? NSDictionary { // dictionary
if let locationsArray = jsonData["locations"] as? NSArray { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["location_name"] as? NSString {
println(location)
}
}
NSUserDefaults.standardUserDefaults().setObject(locationsArray, forKey: "locationArray")
}
}
println(save.dictionaryRepresentation())
You can try this:
Writing
let locationArray = ["London", "NewYork", "Rome"]
let locationData = NSKeyedArchiver.archivedDataWithRootObject(locationArray)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "Location")
NSUserDefaults.standardUserDefaults().synchronize()
Reading
let locationData = NSUserDefaults.standardUserDefaults().objectForKey("Location") as? NSData
if let locationData = locationData {
let locationArray = NSKeyedUnarchiver.unarchiveObjectWithData(locationData) as? [String]
if let locationArray = locationArray {
println(locationArray)
}
}

Resources