快速解决冲突的结构值类型 [英] Resolving conflicting struct value types in swift

查看:60
本文介绍了快速解决冲突的结构值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITableViewController.每行都由一个全局数组填充.这个全局数组描述了一个任务的标题.每个任务都有一些相关联的字符串变量.

I have a UITableViewController. Each row is populated from a global array. This global array Describes the title of a task. Each task has some associated variables which are strings.

我希望能够点击表视图控制器中的任务标题,并将关联的变量链接到该标题.当最终用户从全局数组中添加或删除标题时,全局数组将增长和缩小.

I want to be able to click on the title of task in the table view controller and have the associated variables linked to that title. The global array will be grow and shrink as the end user appends or removes titles from the global array.

这是一个结构体.该结构包含特定变量.

This is made with a struct. The struct contains the specific variables.

这个例子中的问题出现在load函数中.我无法加载数据,因为 Programs = loadedData 无法将类型 '[String]' 的值分配给类型 '[Item].

The problem occurs in this example in the load function. I cannot load the data because Programs = loadedData Cannot assign value of type '[String]' to type '[Item].

import UIKit



struct Item {
let title:String
let others:[String]
}

  var Programs = [Item]()

  class ProgramList: UIViewController, UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var programTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    load()
}


override func viewDidAppear(_ animated: Bool) {
    programTableView.reloadData()
    save()
}


//saving current state of programs array
func save(){
    UserDefaults.standard.set(Programs, forKey: "notes")
}

//loading saved program array
func load() {
    if let loadedData: [String] = UserDefaults.standard.value(forKey: "notes") as? [String] {
        Programs = loadedData
        programTableView.reloadData()
    }
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Programs.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
    cell.programTitle.text = Programs[indexPath.row].title
    return cell
}


//Removing Item by swipping left & saving this newly established array
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCell.EditingStyle.delete {
        Programs.remove(at: indexPath.row)
        programTableView.reloadData()
        save()
    }

}

}

推荐答案

您需要

programs = loadedData.map { Item(title:$0,others:[])}

顺便说一句,你可以让它像 Codable 一样

Btw you can make it Codable like

struct Item:Codable {

并使用编码器/解码器保存/加载它

and save/load it with encoder/decoder

这篇关于快速解决冲突的结构值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆