简体   繁体   English

Append 使用 Swift 将结构转换为数组(在 iOS 中失败,但在 Playgrounds 中失败)

[英]Append a Struct to an Array using Swift (fails in iOS but not in Playgrounds)

This is driving me crazy.这真让我抓狂。 This generic code creates an array of Structs and appends a new element, It runs fine in PlayGrounds or a macOS Command Line Tool project but.此通用代码创建一个结构数组并附加一个新元素,它在 PlayGrounds 或 macOS 命令行工具项目中运行良好,但是。 if you paste it to an iOS project (eg: inside your ViewController) it fails.如果您将其粘贴到 iOS 项目(例如:在您的 ViewController 中)它会失败。 it does not recognizes quiz as an array?它不将测验识别为数组? Why.为什么。 Help/Solution is appreciated.帮助/解决方案表示赞赏。 Thanks!谢谢!

struct Question {
    let text: String
    let answer: String
    
    init(q: String, a: String){
        text = q
        answer = a
    }
}
    
var quiz = [
    Question(q: "A slug's blood is green.", a: "True"),
    Question(q: "Sky is blue", a: "True")
]

quiz.append(Question(q: "Ice is pink", a: "False")) //ERROR: Invalid redeclaration of 'quiz()'

Your quiz.append statement is not in any executable function, so it's like initializing a brand new instance of an object called "quiz", hence you get the "redeclaration" error.您的quiz.append语句不在任何可执行的 function 中,所以这就像初始化 object 的全新实例,称为“测验”,因此您会得到“redeclaration”错误

In Playgrounds, I believe it executes the statements for you, like a script, so you're not required to put it in another method to be called at a later time.在 Playgrounds 中,我相信它会像脚本一样为您执行语句,因此您无需将其放入另一个方法中以便稍后调用。

Put the quiz.append statement in a func like so, and the error should go away:将 quiz.append 语句放在这样的 func 中,错误应该 go 消失:

func quizAppend(q: Question) {
  quiz.append(q)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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