1

I was learning S.O.L.I.D right now from the book iOS programming Big Nerd Ranch. I want to make a an array from convenience init but I have a problem, I want to display the text and image like the exact order of an array but I don't know how. here I show you my code

This is my item class

class Item: NSObject {
var imageName: String
var label: String

init(imageName: String, label: String) {
    self.imageName = imageName
    self.label = label

    super.init()
}

convenience init(list: Bool = false) {
    if list {
        let imageList = ["milada-vigerova", "david-rodrigo", "quran"]
        let labelList = ["Fiqih", "Hadist", "Tafsir"]

        let sortImageName = imageList[imageList.count - 1]
        let sortLabel = labelList[labelList.count - 1]

        self.init(imageName: sortImageName, label: sortLabel)
    } else {
        self.init(imageName: "", label: "")
    }
  }
}

this my ItemStore class that create an array from Item class

class ItemStore {
var allItems = [Item]()

@discardableResult func createItem() -> Item {
    let newItem = Item(list: true)
    allItems.append(newItem)

    return newItem
}

// I make this for in loop to make the table view numberOfSection will return 3 of an allItems
init() {
    for _ in 0..<3 {
        createItem()
    }
  }
}

Please help me

1 Answer 1

3

Good Lord, this is pretty nerdy and cumbersome code.

First of all a struct is sufficient, you get the initializer for free

struct Item {
    let imageName: String
    let label: String
}

In ItemStore create the array instantly

class ItemStore {
    var allItems = [Item]()

    func createArray() {
        allItems = [Item(name: "Fiqih", image: "milada-vigerova"),
                    Item(name: "Hadist", image: "david-rodrigo"),
                    Item(name: "Tafsir", image: "quran")]
    }
}

In the table view return allItems.count in numberOfRows (not numbersOfSection)

Sign up to request clarification or add additional context in comments.

1 Comment

haha my nerdy just because I follow that book, I see so as long as the S.O.L.I.D principles being applied code like above does not matter right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.