这是我的第一篇文章,我很高兴加入这个社区.我正和Ray Wenderlich的视频教程学习 Swift.我在第3课中遇到的挑战是删除数组中的元素而不对索引进行硬编码.我理解Ray提供的正确答案,但只是
正确答案:
// Make an array with "C", "C++", and "Objective-C" var programmingLanguages = ["C", "C++", "Objective-C"] // Append "Swift" to the array programmingLanguages += "Swift" // Insert "Javascript" at Index 2 programmingLanguages.insert("Javscript", atIndex: 2) // Remove "Objective-C" (without hard-coding the index) let optIndex = find(programmingLanguages, "Objective-C") if let defIndex = optIndex { programmingLanguages.removeAtIndex(defIndex) } programmingLanguages
我的回答1:
// Make an array with "C", "C++", and "Objective-C" var programmingLanguages = ["C", "C++", "Objective-C"] // Append "Swift" to the array programmingLanguages += "Swift" // Insert "Javascript" at Index 2 programmingLanguages.insert("Javscript", atIndex: 2) // Remove "Objective-C" (without hard-coding the index) programmingLanguages.removeAtIndex(find(programmingLanguages,"Objective-C") programmingLanguages
我的回答2:
// Make an array with "C", "C++", and "Objective-C" var programmingLanguages = ["C", "C++", "Objective-C"] // Append "Swift" to the array programmingLanguages += "Swift" // Insert "Javascript" at Index 2 programmingLanguages.insert("Javscript", atIndex: 2) // Remove "Objective-C" (without hard-coding the index) let optIndex = find(programmingLanguages, "Objective-C") programmingLanguages.removeAtIndex(optIndex) programmingLanguages当你使用find()时,不能保证返回结果(这里会发生什么?:find(programmingLanguages,“rick astley”))
为了解释这种可能性,find()返回一个“optional” – 这基本上只是意味着当它找不到匹配时它将返回nil.
为了防止您在某些不知道如何处理它的地方意外使用nil,该语言认为选项是一种不同的类型.简而言之,当您获得可选值时,必须检查nil.
执行此操作的主要方法是使用“if let”语法 – 如Ray的示例中所示 – 但更简洁(也更常见)的方法是这样做:
if let defIndex = find(programmingLanguages, "Objective-C") { programmingLanguages.removeAtIndex(defIndex) }
如果您确定可选项不是nil(就像您正在检查刚才插入的内容一样),您可以使用“强制解包”从可选中获取值(并且如果它为零则会导致错误和崩溃) .
你使用强制解包操作符强制解包,感叹号!:
// defIndex is an optional let defIndex = find(programmingLanguages, "Objective-C") // defIndex! <-- unwraps the optional but raises an error if it's nil programmingLanguages.removeAtIndex(defIndex!)