Swift开发报错求助:两类语法问题的快速修复方案咨询
Hey there! Let's tackle these two Swift errors one by one to get your code working smoothly again.
1. Fix for "Value of type 'UIViewController' has no member 'indexOf'"
This error has two easy-to-fix causes:
- Swift 3+ renamed the old array method
indexOf()tofirstIndex(of:). - Your code has a syntax mistake with the empty
()->()placeholder, which doesn’t make sense in this context.
You’re trying to find the index of a view controller in the navigation stack, so you need to pass a specific view controller instance to firstIndex(of:). Here’s the corrected code snippet:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // First, get a reference to the view controller you want to locate in the stack guard let targetVC = self.navigationController?.topViewController else { return 0 // Fallback if we can't access the target view controller } // Use firstIndex(of:) instead of the outdated indexOf() if let index = navigationController?.viewControllers.firstIndex(of: targetVC) { let question = questionsList[index] // Replace with your actual count logic (e.g., return the number of question options) return question.options?.count ?? 0 } return 0 // Fallback if the index isn't found }
2. Fix for "Instance member 'questionsList' of type 'QuestionController' cannot be used on instance of nested type 'QuestionController.QuestionController'"
This happens when you’ve accidentally created a nested type (like a class or struct) inside your QuestionController class that shares the exact same name. The compiler gets confused between the outer QuestionController (where questionsList lives) and the nested one.
Here are two straightforward fixes:
- Option 1: Rename the nested type (recommended)
Avoid name collisions entirely by giving the nested type a unique, descriptive name. For example:class QuestionController: UIViewController { var questionsList: [Question] = [] // Rename the nested type to something distinct class QuestionDetailController { // If you need to access questionsList, add a reference to the parent controller weak var parent: QuestionController? func loadQuestionData() { if let questions = parent?.questionsList { // Use the questionsList here } } } } - Option 2: Explicitly reference the outer instance
If you must keep the nested type’s name, make sure you’re accessingquestionsListfrom the outerQuestionControllerinstance. For example, if you’re inside the nested type, pass a reference to the parent controller when initializing it.
内容的提问来源于stack exchange,提问作者sheishistoric
相关产品推荐
相关产品推荐

