I have code:
struct FilesToDownload {
var fileInternetUrl: String?
var fileName: String?
var savedURL: String?
var productImageUrl: URL?
var fileSize: Int
}
var filesToDownload = [FilesToDownload]()
let fileToDelete = "img1000.jpg"
How can I delete one, selected file from array (to delete: fileToDelete)?
You can try
filesToDownload = filesToDownload.filter { $0.fileName != fileToDelete }
Get the index of the object that you want to delete and remove it:
var filesToDownload = [FilesToDownload]()
let fileToDelete = "img1000.jpg"
// get the index or nil if the array does not contain a file with the given name
let fileToDeleteIndex = filesToDownload.index { $0.fileName == fileToDelete }
// if there is a file -> delete it
if let fileToDeleteIndex = fileToDeleteIndex {
filesToDownload.remove(at: fileToDeleteIndex)
}
First find targeted item index and delet. simple!!
if let index = filesToDownload.index(where: {$0.fileName == fileToDelete} ) {
filesToDownload.remove(at: index)
}
Related
I want to create array of array
ex-
let myImages: [[String]] = [
["image_url_0_0", "image_url_0_1", "image_url_0_2", "image_url_0_3"],
["image_url_1_0", "image_url_1_1", "image_url_1_2"],
["image_url_2_0", "image_url_2_1", "image_url_2_2", "image_url_2_3", "image_url_2_4"]
]
I tried this, but it doesn't work perfectly.
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
But I get result in this form
[["image_url_0_0"], ["image_url_0_0","image_url_0_1"], ["image_url_0_0","image_url_0_1","image_url_0_3"].....]
How should I do this?Please Help.
You try this
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
let arr : [String] = []
for customParams in custom_attributes! {
if(customParams["attribute_code"] as! String == "small_image")
{
print(customParams["value"])
var myString = customParams["value"] as! String
arr.append(myString)
}
}
myArray.append(arr)
}
First you need to create simple string array and then append this array to your myArray. Check following code may be it's help
var myArray :[[String]] = []
for custom_attributes! in items { // items is the json items array
var arrImage: [String] = []
for customParams in custom_attributes! {
if let attCode = customParams["attribute_code"] as? String, attCode == "small_image" {
print(customParams["value"])
var myString = customParams["value"] as! String
arrImage.append(myString)
}
}
myArray.append(arrImage)
}
if I define array as like this means
var tempArray = [String]()
tempArray = ["Hai", "Hello", "How are you?"]
let indx = tempArray.index(of:"Hai")
there is an option
index(of:)
to find index but if I define like this means
var tempArray = [AnyObject]()
//or
var tempArray = [[String:AnyObject]]()()
there is no option to find index
In Swift.swift you can see this declaration:
extension Collection where Iterator.Element : Equatable {
public func index(of element: Self.Iterator.Element) -> Self.Index?
}
This method is available only for array with Equatable elements; AnyObject doesn't conform to Equatable
EDITED:
you can, though, look for your element like this:
var tempArray = [AnyObject]()
for item in tempArray {
if let typedItem = item as? SomeYourType {
if typedItem == searchItem {
}
}
}
EDITED:
for removing you can use something like this (not tested):
someArr.filter({object in guard let typedObject = (object as? YourType) else {return true}; return typedObject != yourObject })
I am try to implement search bar to my table view. But I am getting this error in one function. Don't know how to solve??
Value of type '[Businessdata]' has no member 'objectAtIndex'
My code
var arrDict = [Businessdata]()
func searchMethod(notification:NSNotification)
{
isSearching = true;
let text:String = notification.userInfo!["text"] as! String;
arrSearch = [];
for(var i=0;i<arrDict.count;i++)
{
if((arrDict.objectAtIndex(i).objectForKey("name")?.lowercaseString?.containsString(text.lowercaseString)) == true)
{
arrSearch.addObject(arrDict.objectAtIndex(i));
}
}
TableViewList.reloadData();
}
Edited :
import UIKit
class Businessdata: NSObject {
var BusinessName: String?
var BusinessEmail: String?
var BusinessLatLng: NSArray?
var Address: String?
var ContactNumber: String?
var WebsiteUrl: String?
var Specialities:Array<String>?
var StoreImages: NSArray?
var Languages:Array<String>?
var PaymentMethod:Array<String>?
var OpenHours: [NSDictionary]?
var Rating: Float?
var Updated_date: String?
var FeaturedBusiness: NSDictionary?
init(json: NSDictionary)
{
self.BusinessName = json["business_name"] as? String
self.BusinessEmail = json["business_email"] as? String
self.BusinessLatLng = json["latlng"] as? NSArray
self.Address = json["location"] as? String
self.ContactNumber = json["phone_no"] as? String
self.WebsiteUrl = json["website_url"] as? String
self.Specialities = json["specialities"] as? Array<String>
self.StoreImages = json["images"] as? NSArray
self.Languages = json["languages"] as? Array<String>
self.PaymentMethod = json["method_payment"] as? Array<String>
self.OpenHours = json["opening_hours"] as? [NSDictionary]
self.Rating = json["__v"] as? Float
self.Updated_date = json["updated_at"] as? String
if((json["featured_business"]) != nil)
{
self.FeaturedBusiness = json["featured_business"] as? NSDictionary
}
}
}
Here i have posted the Bussinessdata class code.Now how to solve for my problem
Help me out!!
There is no objectAtIndex in an array. You need to do something like this:
arrDict[i]
Instead of
arrDict.objectAtIndex(i)
Edit
As we discussed in the comments this is what you need
if((arrDict[i].name.lowercaseString?.containsString(text.lowercaseString)) == true)
Try this one:
func searchMethod(notification:NSNotification)
{
isSearching = true;
let text:String = notification.userInfo!["text"] as! String;
arrSearch = [];
for(var i=0;i<arrDict.count;i++)
{
if((arrDict[i].BusinessName.lowercaseString?.containsString(text.lowercaseString)) == true)
{
arrSearch.addObject(arrDict[i]);// or arrSearch.append(arrDict[i])
}
}
TableViewList.reloadData();
}
objectAtIndex: belongs to NSArray and objectForKey: belongs to NSDictionary.
Both are not available for the Swift native types.
But there are two fatal issues:
Businessdata is a custom class which does not respond to objectForKey: at all, and there is no property name in the class.
Assuming you are talking about the property BusinessName and the logic is supposed to filter all Businessdata instances whose lowercase string of BusinessName contains the search string you might write
arrSearch = [Businessdata]()
for item in arrDict {
if let businessName = item.BusinessName as? String where businessName.lowercaseString.containsString(text.lowercaseString) {
arrSearch.append(item)
}
}
or swifiter
arrSearch = arrDict.filter({ (item) -> Bool in
if let businessName = item.BusinessName as? String {
return businessName.lowercaseString.containsString(text.lowercaseString)
}
return false
})
And please conform to the naming convention and use always variable names starting with a lowercase letter.
I have a rss link which I parse it using SWXMLHash and then I use it's elements like below but when an element is missing in the rss I get below error message!
how can I check if rss contain for example source element if it doesn't contain it put " " in the variable !
code :
UPDATE :
Fixed Code :
let count = xml["rss"]["channel"]["item"].all.count
var Name = ""
var Image = ""
var Link = ""
for var index = 0; index < count; index++ {
Name = xml["rss"]["channel"]["item"][index]["title"].element!.text!
if let element = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String? {
Image = element
Link = element
} else {
print("Blank")
Image = ""
Link = ""
}
let ap = pic(name: Name ,img : Image, link : Link)
self.tableData.append(ap)
//for reducing delay of loading table view data
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
you should check for optional where you have force unwrap element, if it has element take value else put ""
let count = xml["rss"]["channel"]["item"].all.count
let arrSource:NSMutableArray = []
for var index = 0; index < count; index++ {
if let element = xml["rss"]["channel"]["item"][index]["source"].element?.attributes["url"] as String? {
print("Element \(element)")
arrSource.addObject(element)
} else {
print("Blank")
}
}
print("Count \(arrSource.count) Arr \(arrSource)")
This works when source or url is empty and prints Blank if one of them are empty
I'm trying to access the url of an object stored in an array, but I'm getting errors no matters what methods I'm using.
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos[i].url
}
Here I get
Could not find member 'url'
and with a foreach:
for photo in userPhotos {
Utils.getImageAsync(photo.url , completion: { (img: UIImage?) -> () in
})
}
I get:
'[ModelAttachment]?' does not have a member named 'Generator'
My array is var photos: Array<ModelAttachment>? and my ModelAttachment looks like this:
class ModelAttachment :Model {
var id: String?
var url: String?
var thumb: String?
}
Any pointers to what I'm doing wrong would be great :)
Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.
if let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment]
{
for object in photos {
let url = object.url
}
}
There's also guard let else instead of if let if you prefer having the result available in scope:
guard let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment] else
{
// break or return
}
// now 'photos' is available outside the guard
for object in photos {
let url = object.url
}
Your userPhotos array is option-typed, you should retrieve the actual underlying object with ! (if you want an error in case the object isn't there) or ? (if you want to receive nil in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map, like this:
let urls = userPhotos?.map{ $0.url }
You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code.
The following is working for me:
class ModelAttachment {
var id: String?
var url: String?
var thumb: String?
}
var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"
var imgs: Array<ModelAttachment> = [modelAttachementObj]
for img in imgs {
let url = img.url
NSLog(url!)
}
See docs here
The photos property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}