Created
November 26, 2019 02:56
-
-
Save ppth0608/13faea559629e3e0747853a69aa683f5 to your computer and use it in GitHub Desktop.
How to implement Marker protocol in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
protocol Paper {} | |
class APaper: Paper { | |
var a: String | |
var text: String | |
init(a: String, text: String) { | |
self.a = a | |
self.text = text | |
} | |
} | |
class BPaper: Paper { | |
var b: String | |
var text: String | |
init(b: String, text: String) { | |
self.b = b | |
self.text = text | |
} | |
} | |
struct Box { | |
var title: String | |
var text: String | |
static let none = Box(title: "", text: "") | |
} | |
protocol Reader { | |
associatedtype Item | |
init() | |
func wrapping(paper: Item) -> Box | |
} | |
struct APaperReader: Reader { | |
init() { } | |
func wrapping(paper: APaper) -> Box { | |
return Box(title: paper.a, text: paper.text) | |
} | |
} | |
struct BPaperReader: Reader { | |
init() { } | |
func wrapping(paper: BPaper) -> Box { | |
return Box(title: paper.b, text: paper.text) | |
} | |
} | |
func wrapping<T: Reader>(ofType: T.Type, paper: T.Item) -> Box where T.Item == APaper { | |
return ofType.init().wrapping(paper: paper) | |
} | |
func wrapping<T: Reader>(ofType: T.Type, paper: T.Item) -> Box where T.Item == BPaper { | |
return ofType.init().wrapping(paper: paper) | |
} | |
let aPaper = APaper(a: "a", text: "ATEST") | |
let aBox = wrapping(ofType: APaperReader.self, paper: APaper(a: "a", text: "ATEST")) | |
print(aBox.title, aBox.text) | |
let bPaper = BPaper(b: "b", text: "BTEST") | |
let bBox = wrapping(ofType: BPaperReader.self, paper: BPaper(b: "b", text: "BTEST")) | |
print(bBox.title, bBox.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment