How to create an array of classes in Swift

I created two classes: StepsCell and WeightCell

import UIKit

class StepsCell {
    let name = "Steps"
    let count = 2000
}


import UIKit

class WeightCell {

    let name = "Weight"
    let kiloWeight = 90
}

In my VC, I am trying to create a cellArray array to hold objects.

import UIKit

class TableViewController: UIViewController {

    var stepsCell = StepsCell()
    var weightCell = WeightCell()

    override func viewDidLoad() {
        super.viewDidLoad()

        var cellArray = [stepsCell, weightCell]
        println(StepsCell().name)
        println(stepsCell.name)
        println(cellArray[0].name)
}

but when I index into an array:

println(cellArray[0].name)

I get zero .. Why? How can I create an array that “holds” these classes and which I can index to get various variables (and functions that will be added later). I thought it would be a very simple thing, but I can not find the answers to it. Any ideas?

+1
source share
2 answers

, . - , cellArray[0]. , AnyObject. -, name, nil.

, println((cellArray[0] as StepsCell).name), :

protocol Nameable {
    var name: String { get }
}

class StepsCell: Nameable {
    let name = "Steps"
    let count = 2000
}

class WeightCell: Nameable {
    let name = "Weight"
    let kiloWeight = 90
}

var stepsCell = StepsCell()
var weightCell = WeightCell()

var cellArray: [Nameable] = [stepsCell, weightCell]
println(StepsCell().name)
println(stepsCell.name)
println(cellArray[0].name)
+8

@Rengers , , , :

class StepsCell {
let name = "Steps"
let cellCount = 2000
}

class WeightCell {
let name = "Weight"
let weightCount = 90
}


var stepcell = StepsCell() // creating the object
var weightcell = WeightCell()


// Your array where you store both the object
var myArray = [stepcell,weightcell];

// creating a temp object for StepsCell
let tempStepCell = myArray[0] as StepsCell

println(tempStepCell.name)

, , , -

((myArray[0]) as StepsCell ).name

, , , ,

if let objectIdentification = myArray[0] as? StepsCell {
println("Do operations with steps cell object here")
}else{
println("Do operation with weight cell object here")

}
+2

Source: https://habr.com/ru/post/1618159/


All Articles