Common classes with Swift protocols

I have a basic protocol:

public protocol BasicSwiftClassLayout { var nibName: String { get } }

and my class:

public class BasicSwiftClass<Layout: BasicSwiftClassLayout> {}

I defined two different structures so that I can initiate this class with two different feathers:

public struct NormalLayout: BasicSwiftClassLayout { public let nibName = "NormalLayoutNibName" }

and

public struct OtherLayout: BasicSwiftClassLayout { public let nibName = "OtherLayoutNibName }

I now have 2 questions based on this.

  • I want to use the Layout variable to retrieve the name of the element that was launched by this class. Therefore, if I were to initiate this class as follows: let myView = BasicSwiftClass<NormalLayout>I want to get nibName for NormalLayout in the class ("NormalLayoutNibName"). I would think of doing something like let myNib = Layout.nibName, but it just tells me Instance member nibName cannot be used on type LayoutSo, how do I find the name nibName?

  • , , public class BasicSwiftClass, classForCoder MyProject.BasicSwiftClass. , , classForCoder MyProject.BasicSwiftClass<Layout.NormalLayout>, let bundle = Bundle(for: classForCoder) classForCoder? - ?

!

+4
1

BasicSwiftClass , BasicSwiftClassLayout, , nibName , , , :

public protocol BasicSwiftClassLayout {
    static var nibName: String { get }
}

public struct NormalLayout: BasicSwiftClassLayout {
   public static let nibName = "NormalLayoutNibName"
}

public struct OtherLayout: BasicSwiftClassLayout {
   public static let nibName = "OtherLayoutNibName"
}

, , Bundle(for class: AnyClass) , . , - , , , , , , :

  • / , . , public struct DifferentLayout: BasicSwiftClassLayout, BasicSwiftClass<DifferentLayout> , BasicSwiftClass, , , ?

  • BasicSwiftClass<OtherLayout>, , . -, , .

, , BasicSwiftClass<Layout>, Bundle(for:) . , , , , , .

:

, , BasicSwiftClass. :.

public protocol BasicSwiftClassLayout: class {
    static var nibName: String { get }
}

final public class NormalLayout: BasicSwiftClassLayout {
   public static let nibName = "NormalLayoutNibName"
}

public class BasicSwiftClass<Layout: BasicSwiftClassLayout> {
    func loadFromNib() {
        let view =  Bundle(for: Layout.self).loadNibNamed(Layout.nibName, owner: self, options: nil)?.first
    }
}

, BasicSwiftClass<Layout> Layout, , , . , Swift , ( ) , , , , BasicSwiftClass<Layout> , .

, , , BasicSwiftClass<Layout>, . , , , - , - :

public protocol ViewRepresentable {
    var view: UIView { get }
}

extension BasicSwiftClass<Layout>: ViewRepresentable {
   public var view: UIView { // load the nib, connect outlets and do other setup, then return the appropriate UIView }
}

let array: [ViewRepresentable] = [BasicSwiftClass<IPadLayout>, BasicSwiftClass<NormalLayout>]
array.forEach { self.containerView.addSubview($0.view) }

- .., . BasicSwiftClass<Layout> , . , .

+5

Source: https://habr.com/ru/post/1690986/


All Articles