Why won't Xcode compile the dictionary creation line? - ios

Xcode won't compile the creation of the dictionary, must i update anything or is there something that i am missing?
import Foundation
import UIKit
var dictionary: [String:Int]()

You have combined a type declaration (the colon) and a call to initializer (the empty parentheses after the type).
If you would like to keep the explicit type, you could do it like this:
var dictionary: [String:Int] = [String:Int]()
However, specifying the type is not necessary, because Swift figures out the type for you. This declaration is identical, but takes less space:
var dictionary = [String:Int]()

Related

Adding elements to an empty array throws errors

I am trying to added elements to an empty string array and I tried to follow this post add-value-to empty-array but none the options are helping me as they result in Xcode throwing errors each time.
here is the code if have tired:
var tasks = [String]()
tasks += ["something"]
This gave me 6 errors on x code with the first being Consecutive declaration on a line must be separated by ; then it says it's an invalid redeclaration of tasks followed by a bunch of errors saying to make it a func. When I try the .append func instead of += it gives the same errors
Now if I try this:
var tasks = [String]()
var tasks = ["Something"]
it only gives me the invalid redeclaration error but I do not believe this the correct way to add elements to the array
Hopefully, this helps explain my issue and sorry for the weird beginner question but thank for the help in advance
I looked at the code in your pastebin and the issue is that you had both the declaration and assignment on separate lines in the class definition.
class TableViewController: UITableViewController {
//temp list of tasks
var tasks = [Sting]()
//giving some default values in the cell
tasks.append(["something"])
You also spelled String wrong, but that is not relevant for the fix.
Another issue is a type mis-match. You declare an array of String, which would be [String]. However, you are attempting to add an array of String to an another array of String, which is wrong.
tasks.append(["something"])
Instead, you should have
tasks.append("something")
This now adds an element of String to your array of Strings.
Finally, you can do one of two things:
Assign the array at creation
var tasks = ["something"]
or assign it inside a function, like your ViewDidLoad
You can't use += with a [String] (array of Strings) and String.
Here's an example I ran in a playground:
var array: [String] = []
array.append("A")
print(array)
It prints ["A"]. Without seeing your code it will be hard to diagnose if there is another problem.
Update after looking at your code:
var tasks = [Sting]() // Should be String
tasks.append(["something"])
You can't append in the declaration, you'll need to add the append to a function (try viewDidLoad or viewWillAppear to test). ["something"] is an array of String, not a String. You'll need to use "something" instead.

outputting a value to a typedef pointer in swift

I'm almost certain the title of this isn't correct but here goes...
I'm bridging to an Objective-C class to set a typedef. The bridge is set up and I'm able to declare the typedef var correctly.
In Objective-C I also called a method from the same class that, when called, output a value to the variable TestHandle.
var TestHandle : TESTHANDLE
TestInit(&TestHandle)
When I try this using Swift 5 I get this error:
Cannot convert value of type 'inout TESTHANDLE' (aka 'inout UnsafeMutableRawPointer') to expected argument type 'UnsafeMutablePointer<TESTHANDLE?>?' (aka 'Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>')
Any pointers?
Some observations:
TESTHANDLE appears to be an alias for UnsafeMutableRawPointer
&testHandle is taking a reference (a pointer to the location) of the testHandle, producing a value of type inout UnsafeMutableRawPointer
As the error says, your TestInit function takes a variable of type UnsafeMutablePointer<TESTHANDLE?>?, a.k.a. Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>
Swift has some rules about how & automatically bridges to the various pointer types, but to be frank, I don't understand them very well.
As far as I know, the Swift pointer types cannot represent nil (0x000...000). To do that, they need to be wrapped within an optional. So when you see the type
Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>>
It's actually two "semantic" parts:
Optional<UnsafeMutablePointer< Optional<UnsafeMutableRawPointer> >>
↳ A nullable pointer to ... ↳ ... something that's a nullable pointer of unspecified (void) type
The reason you're getting your error is because &testHandle can only bridge your UnsafeMutableRawPointer to a Optional<UnsafeMutablePointer<UnsafeMutableRawPointer>>, but not the required Optional<UnsafeMutablePointer<Optional<UnsafeMutableRawPointer>>> (the difference is in that missing layer of "inner" nullability). To get around this, make your testHandle optional, yourself:
var testHandle: TESTHANDLE? // a.k.a. Optional<TESTHANDLE>, a.k.a. Optional< UnsafeMutableRawPointer>
Then, when you use the & operator, Swift will wrap your value in the required Optional<UnsafeMutablePointer< ... >> outter layer.
typealias TESTHANDLE = UnsafeMutableRawPointer
func testInit(_ p: UnsafeMutablePointer<TESTHANDLE?>?) {
print("Success!")
}
var testHandle: TESTHANDLE? = nil
testInit(&testHandle)

Errors when creating Realm object classes

I'm trying to write a simple app in Swift, backed with Realm. When I write vars within classes, I keep getting errors such as "Property cannot be implicitly #objc because its type cannot be represented in Objective-C". Sometimes these errors (which seem to involve Objective-C, which I'm not using) appear and sometimes they don't--See screenshots below.
I'm an admitted Newbie to Swift, but I thought I understood enough to get started. Specifically:
1) Should I add "#objc" before the class declaration?
2) Should I add "#objc" before the dynamic var declaration?
3) It seems that a Float var must be initialized, but not so for String?
4) Why does the compiler complain about a declaration on one line, but not about identical syntax in the next line?
Would sure appreciate some guidance, or pointers to specific instructions for creating Realm object classes!
I reckon the error comes from calling #objc instead of #objcMembers.
Try change
#objc class Transaction: Object
to
#objcMembers class Transaction: Object
And remove all #objc in front of your dynamic variables. So your final code should look like:
import Foundation
import RealmSwift
#objcMembers class Transaction: Object {
dynamic var picPath: String?
dynamic var transAmount: Float = 0.0
}
#objcMembers class Transaction: Object {
dynamic var currentBalance: Float = 0.0
dynamic var highWaterBalance: Float = 0.0
dynamic var acctName: String?
}
Our fellow Paul Hudson has described this attribute on his site hackingwithswift.

add dictionary to dictionary in swift

according to this page it is possible to add an entire dictionary to another
http://code.tutsplus.com/tutorials/an-introduction-to-swift-part-1--cms-21389
but running the code gave me compilation error
var dictionary = ["cat": 2,"dog":4,"snake":8]; // mutable dictionary
dictionary["lion"] = 7; // add element to dictionary
dictionary += ["bear":1,"mouse":6]; // add dictionary to dictionary
error :
[string: Int] is not identical to UInt8
is there a right way to do this functionality in swift ?
of i should add them 1 by 1 ?
The page you are referring to is wrong, += is not a valid operator for a dictionary, although it is for arrays. If you'd like to see all the defined += operators, you can write import Swift at the top of your playground and command+click on Swift, then search for +=. This will take you to the file where all of the major Swift types and functions are defined.
The page you linked to also includes some other erroneous information on quick glance in the array section where it says you can do this: array += "four". So, don't trust this page too much. I believe you used to be able to append elements like this to an array in earlier versions of Swift, but it was changed.
The good news is that with Swift you can define your own custom operators! The following is quick implementation that should do what you want.
func +=<U,T>(inout lhs: [U:T], rhs: [U:T]) {
for (key, value) in rhs {
lhs[key] = value
}
}
Almost invariably when swift complains something is not like UInt8, there's a casting error in your code that may not be obvious, especially in a complex expression.
The problem in this case is that the + and += operators are not defined for that data type. A very nifty way to join arrays is described here:
How do you add a Dictionary of items into another Dictionary

Why `final var` is illegal in Dart?

The analyzer doesn't say final var is illegal.
but dart2js says final var is illegal
What is correct? Why?
The keyword var means mutable variable with explicit dynamic type specifier.
The explicit type specifier means that this is not possible specify another type in declaration.
The keyword final means val or immutable variable with unspecified type, with implicit dynamic type.
The implicit type specifier means that this is possible specify other type in declaration.
More precisely variable that declared as val are the value and variable at once.
It are variable because has the runtime storage.
But it are also immutable value that can be retrieved from associated storage just once and can be used anywhere.
Now consider the following code:
final var foo;
This is the same as the following pseudo code:
immutable mutable dynamic foo;
Of course, this will not work.
That is probably a bug in the analyzer. final and var are mutual exclusive.
One of the following is allowed
final identifier
final type identifier
const identifier
const type identifier
var identifier
type identifier
Dart Programming Language Specification (1.2) - Variables
finalConstVarOrType:
final type?
| const type?
| varOrType
;
varOrType:
var
| type
;
EDIT
My DartEditor (Dart VM version: 1.3.0-dev.3.2 (Mon Mar 10 10:15:05 2014) on "linux_x64") shows an error for final var xxx (Members can not be declared to be both 'final' and 'var'.)

Resources