Skip to content

Instantly share code, notes, and snippets.

@yutailang0119
Last active March 1, 2017 01:27
Show Gist options
  • Save yutailang0119/1eb2ee80c60da7a86d503bfe9153aae2 to your computer and use it in GitHub Desktop.
Save yutailang0119/1eb2ee80c60da7a86d503bfe9153aae2 to your computer and use it in GitHub Desktop.
import UIKit
// Genericsだけでreturnの型を決めたい
struct GenerucTest1<ViewType: UIView> {
func loadView() -> ViewType {
return UIView() // error return UIView() as! ViewType
}
}
// Protocolのassociatedtypeで制約をかければできる
// Protocol使えば簡単だけど、他でも準拠できてしまうのを防ぎたい
protocol GenerucTestProtocol {
associatedtype ViewType: UIView
func loadView() -> ViewType
}
struct GenerucTest2: GenerucTestProtocol {
func loadView() -> UIView {
return UIView()
}
}
struct GenerucTest3: GenerucTestProtocol {
func loadView() -> UITableViewCell {
return UITableViewCell()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment