Xcode报错:无法将'[String]'转换为预期的'String'类型求解决
修复Swift中“Cannot convert value of type '[String]' to expected argument type 'String'”错误
错误原因
你遇到的报错是因为Question结构体的answers属性被定义为String类型,但创建quiz数组里的Question实例时,传入的是字符串数组(比如["Heart", "Skin", "Large Intestine"]),类型不匹配导致编译器报错。
修复步骤
- 将
Question结构体中answers的类型改为[String](字符串数组),匹配多选答案的需求 - 同步更新初始化器
init的a参数类型为[String]
修改后的完整代码
调整后的Question结构体
import Foundation struct Question { let text : String // 改为字符串数组类型,适配多选答案 let answers : [String] let rightAnswer: String // 初始化器参数a的类型同步改为[String] init(q: String, a: [String], correctAnswer: String) { text = q answers = a rightAnswer = correctAnswer } }
原quiz数组无需修改(传入的a参数已为数组类型)
let quiz = [ Question(q: "Which is the largest organ in the human body?", a: ["Heart", "Skin", "Large Intestine"], correctAnswer: "Skin"), Question(q: "Five dollars is worth how many nickels?", a: ["25", "50", "100"], correctAnswer: "100"), Question(q: "What do the letters in the GMT time zone stand for?", a: ["Global Meridian Time", "Greenwich Mean Time", "General Median Time"], correctAnswer: "Greenwich Mean Time"), Question(q: "What is the French word for 'hat'?", a: ["Chapeau", "Écharpe", "Bonnet"], correctAnswer: "Chapeau"), Question(q: "In past times, what would a gentleman keep in his fob pocket?", a: ["Notebook", "Handkerchief", "Watch"], correctAnswer: "Watch"), Question(q: "How would one say goodbye in Spanish?", a: ["Au Revoir", "Adiós", "Salir"], correctAnswer: "Adiós"), Question(q: "Which of these colours is NOT featured in the logo for Google?", a: ["Green", "Orange", "Blue"], correctAnswer: "Orange"), Question(q: "What alcoholic drink is made from molasses?", a: ["Rum", "Whisky", "Gin"], correctAnswer: "Rum"), Question(q: "What type of animal was Harambe?", a: ["Panda", "Gorilla", "Crocodile"], correctAnswer: "Gorilla"), Question(q: "Where is Tasmania located?", a: ["Indonesia", "Australia", "Scotland"], correctAnswer: "Australia") ]
内容的提问来源于stack exchange,提问作者D.K Shivashaant
相关产品推荐
相关产品推荐

