简体   繁体   中英

SWIFT: Remove an item from an array of Structs

I have an array of structs and now I want to create functionality that allows me to remove the struct by index path. I understand that structs are immutable, so any advice on how to solve this issue?

The line of code I was using to solve this was:

arrayOfStruct.removeAtIndex(index)

And this led to the error: Immutable value of type '[Struct]' only has mutating members named 'removeAtIndex'

[clarifying edit]

arrayOfStruct is declared within this class as:

var arrayOfStruct: [Struct] {
    return (UIApplication.sharedApplication().delegate as! AppDelegate).arrayOfStruct
}

You have declared an accessor to your AppDelegate memes property as a computed property . Read up on the Swift spec -- computed properties are indeed read-only.

However, a read-only class reference can be used as a through-way to a writable structure within.

Probably you're trying to make an accessor that's not as verbose. Your shortcut will need to be:

MemeMe/MemeTableViewController.swift, line 14-16:

var appDel: AppDelegate {
    return (UIApplication.sharedApplication().delegate as! AppDelegate)
}

And then whereever you had self.memes before replace with self.appDel.memes :

MemeMe/MemeTableViewController.swift, lines 31-33:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return appDel.memes.count
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM