所以我知道一个类只能继承一个类,但可以继承多个协议.我看着这里的一些代码,搞不懂为什么Swift会抛给我一个错误.

protocol PaymentViewModelConfigurable: ViewModelWithResult {
    
}

class ViewModelWithResult {
    func printWithResultClass() {
        print("In View Model with result class")
    }
}

class PaymentViewModel: PaymentViewModelConfigurable {
    
    
}


class MainOne {
    let viewModel: PaymentViewModelConfigurable = PaymentViewModel()
}

所以我假设这是可以的,因为我的PaymentViewModel类继承了一个协议,而该协议继承了一个类.

但是,如果我在我的视图模型上将逻辑更改为继承协议和类,它将很好地?

protocol PaymentViewModelConfigurable: ViewModelWithResult {
    func payments()
}

class ViewModelWithResult {
    func printWithResultClass() {
        print("In View Model with result class")
    }
}

class PaymentViewModel: ViewModelWithResult, PaymentViewModelConfigurable {
    func payments() {
        print("Payments")
    }
}


class MainOne {
    let viewModel: PaymentViewModelConfigurable = PaymentViewModel()
    
    init() {
        viewModel.payments()
    }
}

以下是出现的错误:

'PaymentViewModelConfigurable' requires that 'PaymentViewModel' inherit from 'ViewModelWithResult'

Type 'PaymentViewModel' does not conform to protocol 'PaymentViewModelConfigurable'

推荐答案

所以我知道一个类只能继承一个类,但可以继承多个协议.

不完全是.一个类可以使用conform to个多协议.这可能看起来像是对措辞的迂腐更正,但它实际上是这里问题的核心.一致性和继承功能是相关和相互关联的,但又截然不同.类似地:

该协议继承自一个类.

这是不可能的.

协议声明的:之后的所有内容都不是超类和协议一致性的列表,就像类一样.这是一份requirements份该协议的 list .因此,这份声明:

protocol PaymentViewModelConfigurable: ViewModelWithResult {
    func payments()
}

是这样说的:"PaymentViewModelConfigurable是一种协议,它可以遵循ViewModelWithResult的子类型的任何协议,并且具有func payments()方法.这就好像你已经写了:

protocol PaymentViewModelConfigurable where Self: ViewModelWithResult {
    func payments()
}

错误消息非常明确地说明了这一点:

Untitled 4.swift:11:7: error: 'PaymentViewModelConfigurable' requires that 'PaymentViewModel' inherit from 'ViewModelWithResult'
class PaymentViewModel: PaymentViewModelConfigurable {
      ^
Untitled 4.swift:11:7: note: requirement specified as 'Self' : 'ViewModelWithResult' [with Self = PaymentViewModel]
class PaymentViewModel: PaymentViewModelConfigurable {
      ^

Ios相关问答推荐

无法在fastlane和github操作中从react-native 应用程序构建ios

React Native Text组件内部TextInput组件在iOS上的问题:在TextInput组件内部键入文本时失go 焦点

在Swift5中,将某些属性值从一个类复制到另一个类实例

DriverKit驱动程序中可能存在IOBufferMemoyDescriptor泄漏

在工作表上移动图像SwiftUI

如何在SwiftUI中拥有基于操作系统版本的条件修饰符?

如何为 XCTest、SwiftUI 预览等初始化带有 @MainActor 注释的 Swift 类

SwiftUI:同时拖动父视图和子视图,但手指分开

工具栏底部 iOS 16 - SwiftUI

通过 Rosetta 打开模拟器 xcode 14 以修复滚动

包装在 AnyView 中时 UIViewControllerRepresentable 无法正常工作

带有属性包装器的不可用属性

如何更新推送通知服务证书

Xcode 缺少支持文件 iOS 12.2 (16E227)

在 Swift 中将 HTML 转换为纯文本

使用 Chrome DevTools 调试 iOS 6+7 Mobile Safari

自动布局:是什么创建了名为 UIView-Encapsulated-Layout-Width & Height 的约束?

如何用 CAShapeLayer 和 UIBezierPath 画一个光滑的圆?

Swift 中的日期到毫秒和回溯到日期

如何检测快速touch 或单击的tableView单元格