如何修改在Swift中键入的结构对象?

时间:2017-04-18 20:27:31

标签: swift struct

有没有办法在以下代码中修改x的{​​{1}}属性?

unknown

struct S { var x = 3 } var s = S() var unknown: Any = s 的类型为Any,副本为unknown。虽然s的{​​{1}}可以通过x之类的内容修改,但如何修改s的{​​{1}}?

4 个答案:

答案 0 :(得分:3)

您可以使用条件绑定:

if var s = unknown as? S {
    s.x = 4
    unknown = s
}
else {
    print("unknown is not an S")
}

答案 1 :(得分:1)

您没有指定用例,但我想要这样做的唯一原因是您希望能够为unknown分配多个不同的结构。在这种情况下,协议可能会满足您的需求:

protocol HasX {
    var x: Int {get set}
}

struct S: HasX {
    var x = 3
}

var s = S()

var unknown: HasX = s

unknown.x = 4 // no error

这将限制您只使用HasX所需的属性,但这是我可以考虑在不使用课程的情况下完成此任务的唯一方法。

答案 2 :(得分:0)

进行类型转换: (未知为S).x = 4

答案 3 :(得分:0)

此时,我认为在Swift中直接修改<!doctype html> <html> <head> <meta charset="utf-8"> <title>State Capitals</title> <script> var myQuiz = [{ ques: "What is the capital of California?", choices: ["Los Angeles", "San Francisco", "Sacramento", "San Diego", "Oakland"], correctAnswer: "Sacramento" }, { ques: "What is the capital of Pennsylvania?", choices: ["Pittsburgh", "Philadelphia", "Harrisburg", "Erie"], correctAnswer: "Harrisburg" }, { ques: "What is the capital of Florida?", choices: ["Tallahassee", "Tampa", "Miami", "Jacksonville"], correctAnswer: "Tallahassee" }, { ques: "What is the capital of Georgia?", choices: ["Augusta", "Atlanta", "Savannah"], correctAnswer: "Atlanta" } ]; //end of myQuiz array of objects for (var i = 0; i < myQuiz.length; i++) { document.write(myQuiz[i].ques + "<br />"); for (var j = 0; j < myQuiz[i].choices.length; j++) { document.write("<input type=radio id=myRadio name=radAnswer>" + myQuiz[i].choices[j] + "<br />"); } } </script> </head> <body> </body> </html> x是不可能的,并且它不是必须的。毕竟,键入unknown的结构对象始终是另一个对象的副本,似乎没有必要修改此类副本的内部,因此不会修改原始对象。

我会将这篇文章标记为我的问题的答案,以便未来的读者能够清楚地了解情况,但我也会对所有值得考虑的答案进行投票。