Why is this not working!?
struct ChocolateBox {
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
}
I tried this without the struct, still doesn't work:
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
I have to add initial values into the array for it to work, for example:
var caramelDelight = ["test":"test"]
caramelDelight["flavor"] = "caramel"
Please explain.
Your var caramelDelight = [] doesn't create an empty dictionary.
To create an empty dictionary use [:]() and specify the types of the keys and values, example: var caramelDelight = [String:String]().
There's also this alternative syntax: var caramelDelight: [String:String] = [:].
Also to modify the var in your struct you need to create an instance of the struct first:
struct ChocolateBox {
var caramelDelight = [String:String]()
}
var cb = ChocolateBox()
cb.caramelDelight["flavor"] = "caramel"
println(cb.caramelDelight) // [flavor: caramel]
UPDATE:
You can also create an initializer for your struct if you need to prepopulate the dictionary:
struct ChocolateBox {
var caramelDelight: [String:String]
init(dict: [String:String]) {
self.caramelDelight = dict
}
}
var cb = ChocolateBox(dict: ["flavor": "caramel"])
Of course then you can update the dictionary as usual:
cb.caramelDelight["color"] = "brown"
println(cb.caramelDelight) // [color: brown, flavor: caramel]
That is because caramelDelight is actually an array, not a dictionary. You can fix that by doing var caramelDelight: [String:String] = [:]
Related
jslint tell Unexpected 'for'.
so i think that i must convert for with foreach
but how?
if someone can help
thanks
// Grab the original element
var original = document.getElementsByTagName("noscript")[0];
// Create a replacement tag of the desired type
var replacement = document.createElement("span");
var i;
// Grab all of the original's attributes, and pass them to the replacement
for(i = 0, l = original.attributes.length; i < l; ++i){
var nodeName = original.attributes.item(i).nodeName;
var nodeValue = original.attributes.item(i).nodeValue;
replacement.setAttribute(nodeName, nodeValue);
}
// Persist contents
replacement.innerHTML = original.innerHTML;
// Switch!
original.parentNode.replaceChild(replacement, original);
You have a comma after i = 0, <========
it should be semicolon.
Another issue is declaring l = original.attributes.length you don't need the variable l
just use it as for(i = 0; i < original.attributes.length; ++i){
if you still wanna use a forEach you can do it as:
original.attributes.forEach(element => {
var nodeName = element.nodeName;
var nodeValue = element.nodeValue;
replacement.setAttribute(nodeName, nodeValue);
});
thanks for your answer, i got Uncaught TypeError: original.attributes.forEach is not a function
function Switch() {
var original = document.getElementsByTagName("noscript")[0];
var replacement = document.createElement("span");
original.attributes.forEach(element => {
var nodeName = element.nodeName;
var nodeValue = element.nodeValue;
replacement.setAttribute(nodeName, nodeValue);
});
// Persist contents
replacement.innerHTML = original.innerHTML;
// Switch!
original.parentNode.replaceChild(replacement, original);
}
I'm Trying reorder UICollectionViewcell Images on drag and drop using RealmSwift As database, My UI is not updating on a drag and drop and strange behaviour, some Images are duplicating , my code is Like this
RealmModel As
class StoryAlbumDM: Object {
dynamic var id = 0
dynamic var type = ""
dynamic var isImage: Int = 0
dynamic var textData = ""
dynamic var imageData: NSData? = nil
dynamic var rowId: Int = 0
dynamic var position: Int = 0
dynamic var storyId: Int = 0
dynamic var isCoverImage: Int = 0
dynamic var imagePath = ""
let allStories = List<StoryAlbumDM>()
}
On drag and drop I'm doing Like this
func collectionView(collectionView: UICollectionView, atIndexPath: NSIndexPath, didMoveToIndexPath toIndexPath: NSIndexPath) {
print("moveItemAtIndexPath")
let fromIndexPath: Int = atIndexPath.row
print("from", fromIndexPath)
let toIndexPathInt: Int = toIndexPath.row
print("To", toIndexPath)
let fromData: StoryAlbumDM!
fromData = realm.objects(StoryAlbumDM.self).filter("position = %d AND storyId = %d", fromIndexPath, self.storyID).first!
let toData: StoryAlbumDM!
toData = realm.objects(StoryAlbumDM.self).filter("position = %d AND storyId = %d", toIndexPath, self.storyID).first!
var tempData = StoryAlbumDM()
self.performSelectorOnMainThread(#selector(StoryViewController.updateSrtoryInRealm), withObject: self.collectionView, waitUntilDone: true)
dispatch_async(dispatch_get_main_queue(), {
self.collectionView.performBatchUpdates({
self.collectionView.reloadData()
}, completion: nil)
})
}
func updateSrtoryInRealm() {
self.tempData.type = self.toData.type
self.tempData.isImage = self.toData.isImage
self.tempData.textData = self.toData.textData
self.tempData.rowId = self.toData.rowId
self.tempData.imageData = self.toData.imageData
self.tempData.position = self.toData.position
self.tempData.storyId = self.toData.storyId
self.tempData.isCoverImage = self.toData.isCoverImage
self.tempData.imagePath = self.toData.imagePath
do {
try! realm.write {
self.toData.type = self.fromData.type
self.toData.isImage = self.fromData.isImage
self.toData.textData = self.fromData.textData
self.toData.rowId = self.fromData.rowId
self.toData.imageData = self.fromData.imageData
self.toData.position = self.fromData.position
self.toData.storyId = self.fromData.storyId
self.toData.isCoverImage = self.fromData.isCoverImage
self.toData.imagePath = self.fromData.imagePath
// title.id = temp.id
self.fromData.type = self.tempData.type
self.fromData.isImage = self.tempData.isImage
self.fromData.textData = self.tempData.textData
self.fromData.rowId = self.tempData.rowId
self.fromData.imageData = self.tempData.imageData
self.fromData.position = self.tempData.position
self.fromData.storyId = self.tempData.storyId
self.fromData.isCoverImage = self.tempData.isCoverImage
self.fromData.imagePath = self.tempData.imagePath
}
//}
}
catch {
print("Printed error : ")
}
Problem: Images Are duplicating, Not updating on UI , Reorder strange behaviour, please help me on this
I answered a similar question recently, but I'll re-explain it here. :)
Easily, the best and quickest way to re-order Realm objects inside a Realm file is to make an overarching List object that holds all of the Realm objects of a given type.
For example in this case, you make another object to hold that allStories value you already created:
// Model class that manages the ordering of story album objects
class StoryAlbumDMList: Object {
let allStories = List<StoryAlbumDM>()
}
// Model class for the actual story album objects
class StoryAlbumDM: Object {
dynamic var id = 0
dynamic var type = ""
dynamic var isImage: Int = 0
dynamic var textData = ""
dynamic var imageData: NSData? = nil
dynamic var rowId: Int = 0
dynamic var position: Int = 0
dynamic var storyId: Int = 0
dynamic var isCoverImage: Int = 0
dynamic var imagePath = ""
}
This way, when you want to re-order the list, all you need to do is re-order them inside this array.
Like I said in the other question, one other way you can do it (Which is not as good, but also doesn't require an extra Realm object) is to add another property named orderedIndex, which simply contains a number indicating the numerical order of these objects. When you want to re-order them, it's simply a matter of re-setting these numbers.
Let me know if you need any more clarification!
I know that question has been asked many times, but the solutions didn't work with me. I have the following NSManaged object class:
#NSManaged var cellColor: AnyObject
#NSManaged var des: String
#NSManaged var name: String
#NSManaged var switcher: NSNumber
And when trying to assign this value to a var as a bool when loading the managed object, I get an error. This is an example of assigning the value to a var:
func loadData(){
var appDel = UIApplication.sharedApplication().delegate as AppDelegate
var context = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Row")
var result:NSArray = context.executeFetchRequest(request, error: nil)!
if result.count > 0 {
for i in result{
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher:Bool{
get{
return i.switcher == NSNumber(bool: true)
//the problem happens here
However, when I try a simple example of casting in this way, It works well.
How to solve that ??
I think it just like this:
for i in results {
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher: Bool {
return Bool(i.switcher)
}
}
Didn't test that though.
Using Realm in a Swift application. I'm fetching users from Realm and want to return an array of users (as my app also uses Parse, it's easier if they are all arrays I'm guessing).
Here is my code:
class func fetchUsersFromDB() -> [User]{
var users = [User]()
let realm = Realm()
var allUsers = realm.objects(User)
users = Array(allUsers)
return users
}
When I do a dump of allUsers I can see a Realm result. But when I dump users it shows me the object with default values.
Any ideas what I'm doing wrong?
Here is how I declare the User model
class User: Object {
dynamic var objectId: String = ""
dynamic var username: String = ""
dynamic var password: String = ""
dynamic var emailVerified: Bool = false
dynamic var email: String = ""
dynamic var firstName: String = ""
dynamic var defaultRelationshipId: String = ""
dynamic var picture: NSData = NSData()
dynamic var updatedAt: NSDate = NSDate()
dynamic var createdAd: NSDate = NSDate()
override static func primaryKey() -> String? {
return "objectId"
}
}
I have a datatable with 100,000+ DataRow. Which method is faster to access the collection?
Is there any faster way to process the rows collection ?
Method 1:
var rows= dsDataSet.Tables["dtTableName"].Rows;
int rowCount = dsDataSet.Tables["dtTableName"].Rows.Count;
for (int c = 0; c < rowCount; c++)
{
var theRow = rows[c];
//process the dataRow
}
Method 2:
for (int c = 0; c < dsDataSet.Tables["dtTableName"].Rows.Count; c++)
{
var theRow = dsDataSet.Tables["dtTableName"].Rows[c];
//process the dataRow
}
It is worth noting the most direct way to access cells is via the DataColumn indexer; the data is actually stored in the columns, not the rows (no: really).
So something like:
var table = dataSet.Tables["dtTableName"];
// HERE: fetch the DataColumn of those you need, for example:
var idCol = table.Columns["Id"];
var nameCol = table.Columns["Name"];
// now loop
foreach(DataRow row in table.Rows)
{
var id = (int)row[idCol];
var name = (string)row[nameCol];
// ...
}
However, frankly if you want the best performance, I would start by saying "don't use DataSet / DataTable". That is actually a very complicated model designed to be all kinds of flexible, with change tracking, rule enforcement, etc. If you want fast, I'd use a POCO and something like "dapper", for example:
public class Foo {
public int Id {get;set;}
public string Name {get;set;}
}
...
string region = "North";
foreach(var row in conn.Query<Foo>("select * from [Foo] where Region = #region",
new { region })) // <=== simple but correct parameterisation
{
// TODO: do something with row.Id and row.Name, which are direct
// properties of the Foo row returned
var id = row.Id;
var name = row.Name;
// ...
}
or even skip the type via dynamic:
string region = "North";
foreach(var row in conn.Query("select * from [Foo] where Region = #region",
new { region })) // ^^^ note no <Foo> here
{
// here "row" is dynamic, but still works; not quite as direct as a
// POCO object, though
int id = row.Id; // <=== note we can't use `var` here or the
string name = row.Name; // variables would themselves be "dynamic"
// ...
}