bcse
(Grey Lee)
May 24, 2018, 1:51pm
#1
I am trying to make something works like UICollectionView, which let user implement UICollectionViewDelegate to handle actions. But since I am learning Swift, I would like to make it strong typed.
Here are my 2 attempts of designing the API. Both of them feels unnatural to use. It there a better way to do this?
MyMenu.swift
import Foundation
import UIKit
public protocol MenuItem {}
public protocol MenuDelegate: AnyObject {
associatedtype Item: MenuItem
func menu(_ menu: Menu<Item, Self>, didSelect item: Item)
}
This file has been truncated. show original
MyMenu2.swift
import Foundation
import UIKit
public protocol MenuItem {}
public protocol MenuDelegate: AnyObject {
func menu<T>(_ menu: Menu<T>, didSelect item: T)
}
open class Menu<Item: MenuItem>: UIView {
This file has been truncated. show original
MyMenu3.swift
// No generics, but it feels more natural than MyMenu2
import Foundation
import UIKit
public protocol MenuItem {}
public protocol MenuDelegate: AnyObject {
func menu(_ menu: Menu, didSelect item: MenuItem)
}
This file has been truncated. show original
1 Like
jamieb
(Jamie Bishop)
May 25, 2018, 6:51am
#2
Your third implementation is how most iOS developers, including me, would’ve done this. Casting is fine, and it’s definitely not strange.