我是新来学习迅速和实践UITableView教程,其中包括一个todo列表应用程序。我能描述我的问题的最好方法是,rawValue应该来自TodoList.swift中的“enum Priority{}”定义,但是ChecklistviewController.swift中的“func itemDetailViewController”无法访问它。
托多利斯特·斯威夫特

protocol CaseCountable {
    static var caseCount: Int { get }
}

extension CaseCountable where Self: RawRepresentable, Self.RawValue == Int {
    internal static var caseCount: Int {
        var count = 0
        while let _ = Self(rawValue: count) {
             count += 1
        }
        return count
    }
}

class TodoList {

    enum Priority: Int, CaseCountable {
      case high = 0, medium = 1, low = 2, no = 3
    }
    .
    .
    .

}

ChecklistViewController.swift
class ChecklistViewController: UITableViewController {

    var todoList: TodoList

    private func priorityForSectionIndex(_ index: Int) -> TodoList.Priority? {
       return TodoList.Priority(rawValue: index)
    }

    .
    .
    .

}

extension ChecklistViewController: ItemDetailViewControllerDelegate {
    .
    .
    .
    func itemDetailViewController(_ controller: ItemDetailViewController, didFinishEditing item: ChecklistItem) {

       for priority in 0...(TodoList.Priority.caseCount-1) {
         let currentList = todoList.todoList(for: TodoList.Priority(rawValue: priority)!)
         if let index = currentList.index(of: item) {
             let indexPath = IndexPath(row: index, section: priority.rawValue) //COMPILER ERROR
             if let cell = tableView.cellForRow(at: indexPath) {
                configureText(for: cell, with: item)
             }
         }
    }
    navigationController?.popViewController(animated: true)
}

我试着关注另一篇文章(How do I get the count of a Swift enum?),它展示了一种技术,使您自己的协议名为CaseCountalbe,以便定制一个枚举,使其行为如同符合Swift 4.2中的caseatable一样。不幸的是,我仍然对如何在文件之间传递数据感到困惑。在这种情况下,如何才能从枚举优先级中获取rawValue来消除编译器警告?

最佳答案

您正试图访问rawValue对象的priority。然而,priority实际上是一个Int
如果更改行let indexPath = IndexPath(row: index, section: priority.rawValue)

let indexPath = IndexPath(row: index, section: currentList.priority.rawValue)如果currentList有一个TodoList枚举值,它可能会工作。
让我们回到Swift中枚举的基础。
例如,如果我们有一个名为PhoneType的枚举,其rawValue类型为Int

enum PhoneType: Int {
    case iPhone5s = 568
    case iPhone8 = 667
    case iPhone8Plus = 736
    case iPhoneX = 812
}

然后,我们可以通过传递rawValuePhoneType来创建Int的实例,并在switch或if else语句中使用枚举,如下所示:
let screenHeight = Int(UIScreen.main.bounds.height)

if let type = PhoneType(rawValue: screenHeight) {
    switch type {
    case .iPhone5s: print("we are using iPhone5s and similar phones like SE/5C/5")
    case .iPhone8: print("we are using iPhone 8 and similar phones")
    case .iPhone8Plus: print("we are using iPhone 8plus or 7plus or 6 plus.")
    default: print("and so on...")
    }
}

我希望这能有帮助。

关于ios - Xcode 9.4.1编译器错误,提示“Int”类型的值没有成员“rawValue”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52834744/

10-09 15:43