Passing String array to a function - ios

I am trying to pass an array to a function:
var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)
My function is declares like this:
func setLevelsArray(arr:[String])
{
GamePrefrences.levels_array = arr
}
But on the line i try to call the function it gives with an error:
cannot invoke ... with argument list of type [(String)]
What is the problem? if its possible to provide brief explanation

First of all, your function is not a class level function and you are calling the method directly using class name.
Try like this.
var array:[String] = []
// fill the array
array.append(uniqueId as! String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)
Function declaration.
class func setLevelsArray(arr:[String])
{
GamePrefrences.levels_array = arr
}
or,
var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
let instance = GamePrefrences()//Depends on you, how you defined the initialiser.
instance.setLevelsArray(array)
Your function body.
func setLevelsArray(arr:[String])
{
instance.levels_array = arr
}

please try something like this
func setLevelsArray(arr:[String])
{
let tempArr = arr
GamePrefrences.levels_array = tempArr
}
in Swift Arrays and Dictionary are passed by value not by reference, therefore if you are not changing the values or assigning to any other variable then Swift compiler does not get the copy, instead the variable still lives in the heap. so before assigning i believe it is necessary to copy this into another variable.

You have invalid declaration of an empty array. Here's how to declare empty array:
var array = [String]()

Related

calling an array of dictionaries initialised in a class

what am i doing wrong in swift?
class ActivityDetailsModel {
var ActivityProfile: [[String]]
init(ActivityProfile: [[String]]){
self.ActivityProfile = ActivityProfile
}
}
var act = ActivityDetailsModel(ActivityProfile: ["cell2"+"firName": "two"])
gives Cannot invoke initializer for type 'ActivityDetailsModel' with argument of type (ActivityProfile: [String: String])
The type signature of the variable ActivityProfile is an Array of Array rather than the expected Array of Dictionary.
This uses the alternative syntax to make it clear
class ActivityDetailsModel : Printable {
var activityProfile : [[String:String]]
init(activityProfile: [[String:String]]) {
self.activityProfile = activityProfile
}
var description : String {
return activityProfile.description
}
}
var act = ActivityDetailsModel(activityProfile: [["cell2"+"firName": "two"]])
println(act)
PS: it's easier to read to start variable names with a lowercase letter

Get object type from empty Swift Array

Is there a way to get instance of Array element from the empty array? (I need dynamic properties because I use some KVC methods on NSObject)
import Foundation
class BaseClass: NSObject {
func myFunction() {
doWork()
}
}
class Car: BaseClass {
dynamic var id: Int = 0
}
class Bus: BaseClass {
dynamic var seats: Int = 0
}
var cars = Array<Car>()
What I need is a vay to get instance of empty Car object from this empty array, for example like this:
var carFromArray = cars.instanceObject() // will return empty Car object
I know that I can use:
var object = Array<Car>.Element()
but this doesn't work for me since I get array from function parameter and I don't know it's element class.
I have tried to write my own type that will do this, and it works, but then I cannot mark it as dynamic since it cannot be represented in Objective C. I tried to write extension of Array
extension Array {
func instanceObject<T: BaseClass>() -> T? {
return T()
}
}
but when I use it, it sometimes throws error fatal error: NSArray element failed to match the Swift Array Element type
Swift 3: Get an empty array's element type:
let cars = [Car]() // []
let arrayType = type(of: cars) // Array<Car>.Type
let carType = arrayType.Element.self // Car.Type
String(describing: carType) // "Car"
This seems to work as of Swift 2.0:
let nsobjectype = cars.dynamicType.Element()
let newCar = nsobjectype.dynamicType.init()
Not sure if it will work in earlier versions.
Something like this?
let cars = Array<Car>()
let car = cars.dynamicType.Element()

swift: can I have a property thats actually a reference?

for example.. I want to pass in some dictionaries into a class in its initializer, and i want to reference those dictionaries across my class.. the problem is when I set them as properties, they are actually being copied, not referenced.
example:
var activeDict: [Int: Projectile]
var inactiveDict: [Int: Projectile]
init(inout activeDict: [Int: Projectile], inout inactiveDict: [Int: Projectile]) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
I want to use activeDict, and inactiveDict across my class. I want them to be references of the originals that are being passed in.
You can store an UnsafeMutablePointer to the dictionary, here is an example, tested in playground:
var dict = ["hejj": 1]
class A<T> {
var myDictRef: UnsafeMutablePointer<T>
init(ref: UnsafeMutablePointer<T>) {
self.myDictRef = ref
}
}
let a = A(ref: &dict)
a.myDictRef.memory["asd"] = 3
a.myDictRef.memory
dict
Updated
In your case use it like that:
var activeDict: UnsafeMutablePointer<[Int: Projectile]>
var inactiveDict: UnsafeMutablePointer<[Int: Projectile]>
init(activeDict: UnsafeMutablePointer<[Int: Projectile]>, inactiveDict: UnsafeMutablePointer<[Int: Projectile]>) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
}
whenever you want to use activeDict or inactiveDict, you can call the dictionary behind the pointer with their memory property like:
activeDict.memory[YourKey] = YourValue

Syntax explanation: square brackets in Swift

I'm studying Swift and got confusing with following syntax:
var treasures: [Treasure] = []
Treasure is custom class, declared as follow:
class Treasure: NSObject { }
In Objective-C square brackets mean method, but what do they mean in Swift?
Ok, this is the meaning of
var treasures: [Treasure] = []
var: you are declaring a variable
treasures: the name of your variable
[Treasure]: the type of your variable, in this case the type is Array of Treasure, the compiler will allow you to insert only object of type Treasure in your Array
[]: the actual object (Array) referenced by your variable, in this case an empty Array.
E.g. if you want the Array to hold 2 elements you can write
var treasures: [Treasure] = [Treasure(), Treasure()]
Hope this helps.
Update:
My example can also be written this way
var treasures = [Treasure(), Treasure()]
Infact thanks to the Type Inference the compiler can deduce the type of the variable treasures looking at the type of the assigned value.
[Treasure] is just a syntax sugar for Array<Treasure>.
The same way [String:Treasure] is just a syntax sugar for Dictionary<String,Treasure>.
[] is just an empty array of the type you defined. The same way [:] is an empty dictionary.
When it comes to Swift and square brackets, the rules are simple. They are used only in two situations:
1) working with Array and Dictionary types:
let vectors : [[Int]] = [[1,2,3],[4,5,6]]
let birthBook : [Int:[String]] = [1987:["John","William"], 1990: ["Mary"]]
2) for subscripting objects that support subscripting:
class RouteMapper {
private var routeMap : [String:String] = [:]
subscript(endpoint: String) -> String {
get {
if let route = routeMap[endpoint] {
return route
}
return "/"
}
set(newValue) {
routeMap[endpoint] = newValue
}
}
}
let routeMapper = RouteMapper()
routeMapper["users"] = "/v1/confirmed/users"
let url = routeMapper["admins"]
Since [ and ] are not allowed in custom operators, these are the only usages for now.

Accessing swift array inside a swift dictionary

I have a function is that takes a dictionary, and I need to parse the information inside.
I can get an NSArray out of the dictionary, but shouldn't I be able to access a native swift array?
class func parseResults(resultsDict:Dictionary<String, AnyObject>) -> Array<Track>? {
var results : NSArray = resultsDict["results"] as NSArray // This works
//var results : Array = resultsDict["results"] as Array<AnyObject> // This doesnt work
...
}
A native Swift array is implemented as a struct so it isn't an AnyObject. If you have your dictionary contain <String, Any> instead, it should work since Array does conform to Any.
Array is struct, which is not object so it you can't convert it from AnyObject
On the other hand, NSArray is class, so you can convert it from AnyObject.
You could wrap the array in a class and that will solve your problem
class WrappedArray<T> {
var array = Array<T>()
}
var dict = Dictionary<Int, WrappedArray<Int>>()
dict[0] = WrappedArray<Int>()
dict[0].array.append(0)
dict[0].array.append(1)
...
You could also implement array methods in the wrapper class and forward them to the array
class WrappedArray<T> {
var array = Array<T>()
func append(_ newElement:T) {
self.array.append(newObject)
}
}
Then you can use it like a regular array.
dict[0].append(0)
instead of
dict[0].array.append(0)

Resources