【问题标题】:facing a problem when applying structs to save information from app应用结构保存应用程序信息时遇到问题
【发布时间】:2020-09-20 09:06:06
【问题描述】:
let questions = ["____ Book","File ____"]
let answers = [["Read","Heed","Write","Say"],["lawsuit", "acquisition", "care","office"]]
var answerDict:[String:[Int:Any]] = [String:[Int:Any]]()
var answerChosen:[String] = [String]()



// variables
// keeps track of what qs we at
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0

//var for counting number of time users press button
var ActionCount: Int = 0



//struc for parsing the qs
struct report {
    var question : String
    var AnswersChosen : [String] = [String]()
    var userCount : Int
    

上面是我将结构引入我的测验应用程序的地方。我的结构包括用户当前打开的问题,AnswersChosen 是用户在获得正确问题之前为该问题选择的选项,最后 userCount 是他尝试的次数

//creating array of report struct
var currentReport = [report]()
//currentReport.append(report(question:questions , AnswersChosen:[String](), userCount:0))
        
//array for what users are selecting
answerChosen.append(sender.title(for: .normal)!)
//print (answerChosen)
//currentReport.AnswersChosen = answerChosen
print(answerChosen)
        
//counting number of times wrong button is pressed
ActionCount += 1
//currentReport.userCount = ActionCount
print(ActionCount)
currentReport.append(report(question:questions[currentQuestion] , AnswersChosen:answerChosen, userCount:ActionCount))
print(currentReport)

这是我写下函数和结构实例的地方。目前,这段代码的输出给了我:

这不是我要寻找的输出。因此,我的问题是如何编辑我的代码,以便我能够为每个问题创建一个“报告”,并且每个报告中的 AnswersChosen 仅来自用户当前所在的问题

【问题讨论】:

    标签: swift xcode struct


    【解决方案1】:

    您需要先从数组中过滤掉当前问题。为此,我们首先需要从数组中获取问题

    let question = questions[currentQuestion]
    

    然后我们通过从 currentReport 数组中获取我们找到的第一个来过滤它

    currentReport.first(where: { $0.question == question})
    

    这实际上可以写成一行

    let current = currentReport.first(where: { $0.question == questions[currentQuestion]})
    

    关于结构的一些事情,类型名称应以大写字母开头,属性名称应以小写字母开头。并且属性 userCount 看起来是多余的,因为它始终是所选答案数量的计数。所以结构可以改为

    struct Report {
        var question : String
        var answersChosen = [String]()
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 2014-09-04
      • 1970-01-01
      • 2011-12-02
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多