Addition of 5 random items through ItemStore.swift


#1

Hello,

Xcode Version 9.0 beta 5 (9M202q)
MacBook Pro (13-inch, early 2011)
MacOS Sierra (version 10.12.6)

When I include the init() function in ItemStore class which itself is in the ItemStore.swift file, Xcode displays an alert message which says “Result of call to ‘createItem()’ is unused”.

My question is : If the result of this call is unused, how does the program generate 5 random items to display in the table ?

Please find my code of ItemStore.swift below. Can somebody help me to better understand the logic used in this example ? I am just a hobby programmer, please avoid making fun of me.

import UIKit

class ItemStore {
    var allItems = [Item] ()
    
    func createItem() -> Item {
        let newItem = Item(random: true)
        allItems.append(newItem)
        return newItem
    }

    init() {
        for _ in 0..<5 {
            createItem()
            
        }
    }
    
}

#2

What that warning message says is this: The createItem function is returning a value, but you are not using that value. The function is still creating and adding a new item to the allItems store.

To stop getting that warning you must either use the result returned by the function or explicitly throw it away.

For example, use the result:

...
let result = createItem ()
print (result)
...

Or throw it away:

...
let _ = createItem ()
...


#3

Thanks for the clear explanation ibex10.