Set objects to empty NSDictionary in Swift [duplicate] - ios

This question already has answers here:
Swift dictionary bug?
(6 answers)
Closed 8 years ago.
I can create an NSDictionary
var namesDictionary=Dictionary<String,String>()
namesDictionary["Jacob"] = "Marry"
But, when I create a empty dictionary like coded below, line 1 i okie, but line 2 (adding values) throws an error.
var namesDictionary =[:]
namesDictionary["Jacob"] = "Marry"
Error is "Cannot assign to the result of this expression". Is there any other way to assign the values.

It looks like it's an issue with swift interpreting the type of your dictionary. Try explicitly typing your empty dictionary.
var namesDictionary: Dictionary<String, String> = [:]
namesDictionary["Jacob"] = "Marry"
I think a better use for [:] is for emptying an already defined dictionary. If you add a third line namesDictionary = [:], you will be able to call namesDictionary["Jacob"] = "Marry" again since the compiler knows what type of dictionary it is from the inital declaration.

Related

Cast from 'Double' to unrelated type 'String' always fails [duplicate]

This question already has answers here:
Swift double to string
(16 answers)
Closed 3 years ago.
I'm getting the data from the api response
I decoded the data properly
then I assigned the values to tableview cell
But I'm getting the warning
Cast from 'Double' to unrelated type 'String' always fails
how can I solve this , So that I can assign the double value to the UILabel and get my result
I tried this following code
var rate : Double
cell.priceOfVehicleLabel.text = details.rate as? String
You need
cell.priceOfVehicleLabel.text = "\(details.rate)"
You can use String's init(describing:), i.e.
cell.priceOfVehicleLabel.text = String(describing: details.rate)
It's simply cell.priceOfVehicleLabel.text = String(details.rate).

Swift Can't append to String array [duplicate]

This question already has answers here:
Simple swift array append not working
(3 answers)
Closed 4 years ago.
I have this array defined inside a class:
var pickOption: [String]?
inside my classes init, I am trying to append to the array:
override init!(reuseIdentifier identifier: String!) {
self.pickOption?.append("aaa")
print(self.pickOption)
}
but self.pickOption is returning nil, why? and how can I fix it?
With first statement var pickOption: [String]? you have just declared the array of type string but never allocate the memory. As this is optional type, it will be nil at the time of declaration.
You need to allocate memory for array before using it. You can declare array as this var pickOption = [String]() and rest of code will do the work!!
You have to init it declare it like this
var pickOption = [String]()
as this line
self.pickOption?
with the optional won't run as in it's moment pickOption is nil

What is difference between below 2 lines? [duplicate]

This question already has answers here:
What's the difference between "as?", "as!", and "as"?
(3 answers)
Closed 4 years ago.
I am trying to add code in cellForRowAt indexPath method like below
cell.itemNameLabel.text = nameArray[indexPath.row]
but it is showing error as Cannot assign value of type 'Any' to type 'String?'
so it can be solved by below 2 ways,
cell.fruitName.text = fruitArray[indexPath.row] as? String
or
cell.fruitName.text = (fruitArray[indexPath.row] as! String)
so, my question is what is the difference between 2 answers?
cell.fruitName.text = fruitArray[indexPath.row] as? String
Above return type is optional value. means it will be nil value return if array is not consist string value.
cell.fruitName.text = (fruitArray[indexPath.row] as! String)
Above return type is non-optional value. means it will be fire fatal error if array is not consist string value.
Below is the generic information for all optionals. Please find it.
When you are using ! and the fruitArray[indexPath.row] is nil it will trigger run time error but if use ? it will fail gracefully.
You can find more detail information in Apple document

How do I save a custom class in swift to NSUserDefaults? [duplicate]

This question already has answers here:
Using NSUserDefaults on arrays
(2 answers)
Closed 7 years ago.
I have made a custom class called test. I made a variable called "game" equal to test. I tried to save "game" to NSUserDefaults and attempted to print values from "game". After running the project I got an error: "Thread 1:signal SIGABRT". How do I save my custom object to NSUserDefaults without getting this error?
Here is my class:
class Test {
var boolean = false
var int = 1
var arr = ["one": 1]
}
Here is my saving code:
let defaults = NSUserDefaults.standardUserDefaults()
let game = Test()
game.arr = ["two": 3]
game.hi = true
game.int = 100
defaults.setObject(game, forKey: "SG")
let gameSet = defaults.objectForKey("SG")! as! Test
print(gameSet.int)
print(gameSet.boolean)
print(gameSet.arr["one"])
This is all in the viewDidLoad method. Excluding the test class.
From the documentation:
The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
You'll want to look at using NSKeyedArchiver instead for custom objects.

NSGliff for Swift Dictionary Key - Using uintptr_t?

I need to use an NSGlyph as the key in a Swift dictionary
var glyph:NSGlyph //set to a glyph
var glyphDict:[NSGlyph:CGPath] //Will contain a cache of glyphs previously converted to paths
var path = glyphDict[glyph]
but I get:
error: '[NSGlyph : CGPath]?' does not have a member named 'subscript'
So I guess Apple hasn't defined a subscript for NSGlyph?
I've found this code from Apple's VectorTextLayer Sample Code that successfully uses a CGGlyph as a key in a CFDictionary. How can I adapt this to work in a Swift dictionary?
CGPathRef path = (CGPathRef)CFDictionaryGetValue(glyphDict, (const void *)(uintptr_t)glyph);
I understand that code is wrapping the CGGlyph into a uintptr_t. How could I do this in Swift?
I think you've copied different code in your question. That error happens when the variable you're using as dictionary is an optional, so declared as:
var glyphDict:[NSGlyph:CGPath]?
To solve the issue, you can read from the dictionary using optional chaining:
var path = glyphDict?[glyph]
Note that path is an optional itself.

Resources