You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS开发(Swift):值存在时如何获取对应数组索引的元素值

解决思路与代码实现

Hey there! Let's walk through how to solve this problem step by step—since you're new to iOS development, I'll keep things clear and straightforward. First, let's align on what your code structure likely looks like based on your description:

class Question {
    // 示例:四个不同类型的变量,你可以根据实际需求修改类型和名称
    let title: String
    let correctAnswer: Bool
    let difficultyLevel: Int
    let topic: String
    
    init(title: String, correctAnswer: Bool, difficultyLevel: Int, topic: String) {
        self.title = title
        self.correctAnswer = correctAnswer
        self.difficultyLevel = difficultyLevel
        self.topic = topic
    }
}

class QuestionBank {
    var list = [Question]()
    
    init() {
        // 初始化时添加6个Question实例
        list.append(Question(title: "Swift is statically typed?", correctAnswer: true, difficultyLevel: 1, topic: "Basics"))
        list.append(Question(title: "Let variables can be mutated?", correctAnswer: false, difficultyLevel: 1, topic: "Basics"))
        // ... 继续添加剩下4个Question实例
    }
}

方案1:找到第一个匹配目标值的元素及其索引

If you only care about the first occurrence of your target value, Swift's firstIndex(where:) method is perfect for this. It returns an optional index (since the target might not exist), so we'll use if let to safely unwrap it and avoid crashes.

示例代码

// 初始化你的QuestionBank实例
let questionBank = QuestionBank()

// 假设我们要找"difficultyLevel"等于1的第一个Question
let targetDifficulty = 1

if let matchingIndex = questionBank.list.firstIndex(where: { question in
    // 替换成你要匹配的变量和目标值
    question.difficultyLevel == targetDifficulty
}) {
    // 根据索引获取对应的Question元素
    let matchedQuestion = questionBank.list[matchingIndex]
    
    print("找到匹配元素,索引:\(matchingIndex)")
    print("元素的所有变量值:")
    print("- 标题:\(matchedQuestion.title)")
    print("- 正确答案:\(matchedQuestion.correctAnswer)")
    print("- 难度等级:\(matchedQuestion.difficultyLevel)")
    print("- 主题:\(matchedQuestion.topic)")
} else {
    print("没有找到包含目标值的元素")
}

方案2:找到所有匹配目标值的元素及其索引

If there could be multiple elements with your target value, loop through the array using enumerated() (which gives you both the index and element) to collect all matches.

示例代码

let targetTopic = "Basics"
var allMatches = [(index: Int, question: Question)]()

// 遍历数组,收集所有匹配的元素和索引
for (index, question) in questionBank.list.enumerated() {
    if question.topic == targetTopic {
        allMatches.append((index, question))
    }
}

// 处理结果
if !allMatches.isEmpty {
    print("找到\(allMatches.count)个匹配元素:")
    for match in allMatches {
        print("索引\(match.index):\(match.question.title)")
    }
} else {
    print("没有找到匹配元素")
}

新手友好小提示

  • Never force-unwrap optional indices: firstIndex(where:) returns an optional, so always use if let or guard let instead of !—this prevents crashes if the target value doesn't exist.
  • Clean up your code with methods: Wrap this logic into a method inside QuestionBank to make your code more organized. For example:
    extension QuestionBank {
        func findQuestionsByTopic(_ topic: String) -> [(index: Int, question: Question)] {
            return list.enumerated()
                .filter { $0.element.topic == topic }
                .map { ($0.offset, $0.element) }
        }
    }
    
    // 使用时只需调用
    let topicMatches = questionBank.findQuestionsByTopic("Basics")
    
  • Mutable variables work the same: If your Question properties are declared with var instead of let, the logic stays identical—you'll just be able to modify the matched element's values if needed.

内容的提问来源于stack exchange,提问作者Aristeidis Karavas

火山引擎 最新活动