将类类型作为函数参数传递并用作?上课

帕特里克

有没有办法通过函数传递类类型并尝试将类转换为给定的类类型?我尝试了以下代码。

class Section {}
class TimeSection: Section {}
class TaskSection: Section {}

let timeSection = TimeSection()
let taskSection = TaskSection()

let sections = [timeSection, taskSection]

func findSection(from classType: Section.Type) {
    for section in sections {
        guard let section = section as? classType else { continue }

        print("Found section")
    }
}

findSection(from: TimeSection.self)

但是我总是会收到这个错误:

Use of undeclared type 'classType'
劳斯伯特

斯威夫特4.2

您可以使用泛型函数并将type参数限制为Section。

import Foundation

class Section {}
class TimeSection: Section {}
class TaskSection: Section {}
class NoSection {}

let timeSection = TimeSection()
let taskSection = TaskSection()

let sections = [timeSection, taskSection]

func findSection<T: Section>(from classType: T.Type) {
    for section in sections {
        guard let section = section as? T else { continue }

        print("Found section: \(section)")
    }
}

findSection(from: TimeSection.self) // Found section: __lldb_expr_9.TimeSection
findSection(from: TaskSection.self) // Found section: __lldb_expr_9.TaskSection
findSection(from: NoSection.self) // won't compile

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将类引用作为构造函数参数传递

将类作为函数并用函数类型声明参数类型是否很棒?

将类类型作为参数传递给类构造函数

将函数引用作为参数传递

如何将类类型作为参数传递给函数?

如何将类类型作为函数参数传递

C ++将临时类型名类作为函数参数传递

将函数作为类型未知的类的模板参数传递

将类类型作为构造函数参数传递 C++

如何使用作为参数传递的类的静态函数

将元类型作为函数参数传递

将类作为函数参数传递

将函数作为类中的参数传递

将引用作为参数传递给类的正确方法

C++:将引用作为参数传递,但该函数不接受引用作为参数

Elixir将模块的引用作为函数参数传递

将引用作为函数参数传递不起作用

将类的子类作为类型参数传递(类型参数是子类)

当用作类型参数时,有没有办法将参数传递给类构造函数?

我可以将Class作为枚举的构造函数参数传递,然后将其用作方法的返回类型吗?

将类作为函数参数传递时,C ++不完整类型错误

调用作为参数传递的类方法

将类成员函数作为参数传递给全局函数

将数组作为类构造函数的函数参数传递

将抽象类构造函数作为函数参数传递

使用作为参数传递的函数声明

将方法引用作为参数传递

将类类型作为参数传递并创建它的实例

有没有办法将类类型作为参数传递给函数并在该函数内创建对象?