skip to Main Content

why view inside closure not returning the type of UILabel?

If any other solution is there please do let me know.

extension UIView {
     public func apply( _ action: ((_ view: Self) -> Void)?) {
        
     }
}

let label = UILabel()
label.apply { view in }

screenShot

2

Answers


  1. The Self points to the actual type and the actual type inside the UIView extension is the UIView itself!

    What you are looking for is when you use Self inside a protocol definition which then points to the conforming entity’s type.

    To achieve what you are looking for, you need to use a protocol instead, like this:

    protocol Applicable: AnyObject {
        associatedtype S = Self where S: Applicable
        func apply( _ action: ((_ view: S) -> Void)?)
    }
    
    extension Applicable {
        func apply( _ action: ((_ view: Self) -> Void)?) { action?(self) }
    }
    
    extension UIView: Applicable { }
    

    then:

    Demo

    Login or Signup to reply.
  2. The self inside a closure of a function doesn’t inherently return the type of an extension because closures capture values and context at the time of their creation, not their extension or type information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search