我正在學習斯威夫特。我想刪除UITableViewCellEditingStyle
的帖子,但它不起作用。它顯示:如何解決Swift 3錯誤'不能在不可變值上使用變異成員:'loadedPost'只獲取屬性'?
不能使用不可變值可變成員:「loadedPost」獲得唯一的財產
在該行:
Dataservice.instance.loadedPosts.removeAtIndex(indexPath.row)
如何解決語法?
這是第一次的viewController:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
DataService.instance.loadedPosts.removeAtIndex(indexPath.row) //‘cannot use mutating member on immutable value: ‘loadedPost’ get only property’
self.onPostsLoaded()
}
}
這是陣列中的另一個文件:
class DataService {
static var instance = DataService()
private var _loadedPosts = [Post]()
var loadedPosts: [Post] {
return _loadedPosts
}
func savePosts() {
let postsData = NSKeyedArchiver.archivedData(withRootObject: _loadedPosts)
UserDefaults.standard.set(postsData, forKey: "posts")
}
func loadPosts() {
if let postsData = UserDefaults.standard.object(forKey: "posts") as? Data {
if let postsArray = NSKeyedUnarchiver.unarchiveObject(with: postsData) as? [Post] {
_loadedPosts = postsArray
}
}
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "postsLoaded"), object: nil))
}
func addPosts(post: Post) {
_loadedPosts.append(post)
savePosts()
loadPosts()
}
'loadedPosts'由您定義爲只讀屬性時,'_loadedPosts'的讀寫性能,同時,由你定義。 – holex