Storing Different Types of Value in Array in Swift

Storing different types of value in Array in Swift

From REPL

 xcrun swift
1> import Foundation
2> var test = ["a", "b", true, "hi", 1]
test: __NSArrayI = @"5 objects" {
[0] = "a"
[1] = "b"
[2] =
[3] = "hi"
[4] = (long)1
}
3>

you can see test is NSArray, which is kind of AnyObject[] or NSObject[]

What happening is that Foundation provides the ability to convert number and boolean into NSNumber. Compiler will perform the conversion whenever required to make code compile.

So they now have common type of NSObject and therefore inferred as NSArray


Your code doesn't compile in REPL without import Foundation.

 var test = ["a", "b", true, "hi", 1]
<REPL>:1:12: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible'

 var test:Array = ["a", "b", true, "hi", 1]
<REPL>:4:18: error: cannot convert the expression's type 'Array' to type 'ExtendedGraphemeClusterLiteralConvertible'

but you can do this

var test : Any[] = ["a", "b", true, "hi", 1]

Because they have a common type, which is Any.


Note: AnyObject[] won't work without import Foundation.

var test:AnyObject[] = ["a", "b", true, "hi", 1]
<REPL>:2:24: error: type 'Bool' does not conform to protocol 'AnyObject'

How to store two values with two different key into array or dictionary using Swift?

this may help you ...:)

var data = [Any]()
// call this function on time of get data or adding data
func info (id : Int , name : String){
var information = [id : name]
data.append(information)
}

//this function will generate final formate

func create_formate() -> [String:Any]{
var final_formate = [String:Any]()
final_formate["status"] = true
final_formate["data"] = data

return final_formate
}

Swift: Store multiple Types in a single array

Instead of creating string array you can create the array of car like this and store directly car object

var cars = [Car]()
let mustang = Car() // car is a class name
mustang.brandName = "Ford"
mustang.modelName = "Mustang" // string type
mustang.modelYear = 1968
mustang.isConvertibible = true
mustang.isHatchback = false
mustang.hasSunroof = false // bool type
mustang.numberOfDoors = 2 // int type
mustang.powerSource = "gas engine"
cars.append(mustang)

Or if you want to store different types of object then you cant create array of AnyObject, So that it will store Any type of instance or object inside that array.

var arr = [AnyObject]()
let car = Car()
let bike = Bike()
arr.append(car)
arr.append(bike)

Working with array with different data types in Swift

Use a protocol that has the methods/properties necessary for next and previous actions. Have both of your track types implement the protocol. Have your array have the type of the protocol.

protocol Track {
title: String
albumTitle: String
// other method and properties
}

class JSONTrack: Track {
// implementation
}

class CoreDataTrack: Track {
// implementation
}

let tracks = [Track]()

Is there a way to store arrays in an array in Swift

If you want an array of string arrays then simply do:

var bigArray = [[String]]()
bigArray.append(array)

Swift initialize array with different types

Since Swift compiler is smart enough to deduce the closest common subtype of array initializer expressions, your array element type ends up an NSObject.

Here is a quote from the Swift book:

The final snippet creates a constant array called library, which contains two Movie instances and three Song instances. The type of the library array is inferred by initializing it with the contents of an array literal. Swift’s type checker is able to deduce that Movie and Song have a common superclass of MediaItem, and so it infers a type of [MediaItem] for the library array:

let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]

Array with reference type

In Swift, Array is a value type - so the results of arrayOne would be copied to arrayTwo. However, UIView is a reference type, so the references are copied. The references still point to the original UIView which is why you are seeing this behaviour.



Related Topics



Leave a reply



Submit