How to append an empty value to NSData Array (Swift) - arrays

I have
var images: [NSData] = [];
and I need to add empty values into this array during executing of my for-loop block and then replace these empty values on NSData of the images I downloaded from the server.
How should I append an empty value to NSData-array?
I tried some like ... as! NSData, or create variable someVar: NSData? - app crashes every time

Create an empty Data (NSData in Swift 2) instance and append it to the array
var images: [Data] = []
let emptyData = Data()
images.append(emptyData)

Make an array of optionals var images: [NSData?] = [];
And add nil values when in for-loop images.append(nil)
After that replace with your real data if you know position in array

You could have your array be optional NSData like so:
var images: [NSData?] = [];
That way, you can set nil if you want:
images.append(nil)
And check on the loop:
for imageData in images {
if let data = imageData {
// data exists
} else {
// data doesn't exist yet at this index
}
}

Related

Creating an array out of decoded Firebase data

I am using the pod CodableFirebase to decode Firebase data and am attempting to place that data into an array. The problem I'm having is its placing each instance of data into a separate array causing me issues when I go to IndexPath it for use in a CollectionView.
The Code:
struct WatchList: Codable {
let filmid: Int?
}
var watchList = [WatchList]()
ref.child("users").child(uid!).child("watchlist").observe(DataEventType.childAdded, with: { (info) in
guard let value = info.value else { return }
do {
let list = try! FirebaseDecoder().decode(WatchList.self, from: value)
self.watchList = [list]
print(self.watchList)
self.watchlistCollection.reloadData()
}
}, withCancel: nil)
Here is how the array is printed to the console:
[Film_Bee.ProfileView.WatchList(filmid: Optional(332562))]
[Film_Bee.ProfileView.WatchList(filmid: Optional(369972))]
[Film_Bee.ProfileView.WatchList(filmid: Optional(335983))]
When I use the array within the CollectionView it only counts and indexpaths the last array.
How can I place the data into a single array?
As commented by #vadian replacing
self.watchList = [list]
with
self.watchList.append(list)
Solved the question.

why are my items not going into the array? Xcode and swift NSURLSession

I am using Swift and Xcode, I have built model object with the following variables:
var itemImageNames: [String]?
var itemTitle: String?
var itemDescription: String?
var itemURL: String?
In the mainviewcontroller, I created an variable of model type. I am initiating a NSURLSession...dataTaskWithURL... and adding itemImageNames that I receive back from the server by using append. The data comes back as valid, I've parsed it and it is indeed coming back as Strings. I've tried two solutions,
create a string array out of the images and set that array to self.item.itemImageNames?
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]] {
var imageURLs: [String] = [""]
for dictionary in json {
if let imageURL = dictionary["url"] as? String {
imageURLs.append(imageURL)
print(imageURL)
}
}
self.featuredItem.itemImageNames? = imageURLs
append each of the strings as I get them using self.item.itemImageNames?.append(image)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]] {
for dictionary in json {
if let imageURL = dictionary["url"] as? String {
self.featuredItem.itemImageNames?.append(imageURL)
print(imageURL)
}
}
For some reason, the itemImageNames remains nil, using both approaches. I am sure it will work if I just use one image (e.g. the 1st image), and change itemImageNames to a "String?".
In addition, I can update the itemTitle, itemDescription, and itemURL easily by just setting them to self.item.itemTitle, self.item.itemDescription, self.item.itemURL, respectively. Is there something I'm missing on how to enter information into an array?
In approach #2 initialize the itemImageNames array before trying to append to it. If you try to append to an array that is nil then nothing will happen.
itemImageNames = []
for dictionary in json {
if let imageURL = dictionary["url"] as? String {
self.featuredItem.itemImageNames?.append(imageURL)
print(imageURL)
}
}

Swift: Get multiple array values like "x"

For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']
Is there any simple way to get only the "player_runX.png" images?
You can use filter to get all elements that hasPrefix("player_run"):
let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns) //["player_run0.png", "player_run1.png", "player_run2.png"]
One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:
var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
func getSubArray(array:[String],prefix:String) -> [String]
{
var newArray = [String]()
for img in array
{
if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
{
newArray.append(img)
}
}
return newArray
}
var test = getSubArray(myArray, prefix: "player_run")

How to convert from a Swift String Set to an Array

I am trying to create an array of words from a string object retrieved from Parse. The object retrieved looks like this:
Then this line of code gives this.
let joinedWords = object["Words"] as! String
How do I convert joinedWords to an Array?
If you don't care about the order, you can use flatMap on the set:
var mySet = Set<String>()
for index in 1...5 {
mySet.insert("testwords\(index)")
}
let myArray = mySet.flatMap { $0 }
print(myArray) // "["testwords5", "testwords3", "testwords4", "testwords2", "testwords1"]"
If you want the list sorted alphabetically, you can make your array a var and use sortInPlace()
var myArray = mySet.flatMap { $0 }
myArray.sortInPlace()
print(myArray) // "["testwords1", "testwords2", "testwords3", "testwords4", "testwords5"]"
If object["Words"] is AnyObject, you will have to unwrap it.
if let joinedWordsSet = object["Words"] as? Set<String> {
var joinedWordsArray = joinedWordsSet.flatMap { $0 }
myArray.sortInPlace()
print(myArray)
}
Swift 3 note: sortInPlace() has been renamed sort().
Many thanks to #JAL for so much time on chat to solve this one. This is what we came up with. Its a bodge and no doubt there is a better way!
When uploading to Parse save the set as an array.
let wordsSet = (wordList?.words?.valueForKey("wordName"))! as! NSSet
let wordsArray = Array(wordsSet)
Then it saves to Parse - looking like a set, not an array or a dictionary.
let parseWordList = PFObject(className: "WordList")
parseWordList.setObject("\(wordsArray)", forKey: "Words")
parseWordList.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
// Do something
} else {
print("Error: \(error) \(error?.userInfo)")
}
}
Then you can drop the [ ] off the string when its downloaded from Parse, and remove the , and add some "" and voila, there is an array that can be used e.g. to add to CoreData.
var joinedWords = object["Words"] as! String
joinedWords = String(joinedWords.characters.dropFirst())
joinedWords = String(joinedWords.characters.dropLast())
let joinedWordsArray = joinedWords.characters.split() {$0 == ","}.map{ String($0) } // Thanks #JAL!

Sorting UIImage Type Array in Swift

How do I sort images in order in an array type UIImage?
I'm query images from Parse, putting them in an AnyObject type array and converting it into UIImage type array.
var imagesArray:[AnyObject] = []
var uiImageArray:[UIImage] = []
To display the images I'm doing this:
func updateImageOnUI() { //Changes the UI
if imageCounter < self.imagesArray.count {
var imageElement: AnyObject = self.imagesArray[imageCounter]
var imageUpdate: AnyObject = self.imagesArray[imageCounter]
println(imageUpdate["ImageFiles"])
let userImageFile = imageUpdate["ImageFiles"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData!, error: NSError!) -> Void in
if !(error != nil) {
let image = UIImage(data:imageData)
self.image.image = image
}
}
} else {
imageQuery()
}
}
Problem is, I can't sort the images so that they appear in order. They are named "image1.jpg, image2.jpg, etc"
How do I sort the images so that they repeat in order?
I've tried the sort function, but it's giving me errors
let sortedArray = sorted(imageList, {
(str1:UIImage, str2: UIImage) -> Bool in
return str1. /*not sure what to put*/ > str2./*not sure what to put*/
})
The errors I'm redesign are saying that AnyObject or UIImage aren't compatible types.
It's not possible to get the fileName of an UIImage after it is set.
You could always store the array of UIImages as [(fileName: String, image: UIImage)]. When you insert them, you add the filename (or other name you want to sort by). Then you can sort the array of tuples by fileName.

Resources