Posts

Showing posts with the label Swift

Why implementation of the sequence protocol is said destructive?

Is implementation of sequence protocol , destructive ? Why and how! Sequence type is said to provide sequential, iterated access of its elements.  Think of a sequence generator which can be used to create user id's, from a starting point.   public struct UserIdSequenceGenerator : Sequence {     private var startId : Int          public init (startId: Int ){         self . startId = startId     } } extension UserIdSequenceGenerator : IteratorProtocol {     public mutating func next () -> Int ? {         defer {             startId += 1         }         return startId        } } Requirements on implementing Sequence Protocol. First Approach. Override  make Iterator() method which returns  IteratorProtocol object.   Second Approach Make the UserIdSequenceGenerator...

hitTest on iOS to identify the view being hit

Image
HitTest on iOS Use hitTest, to identify the view being tapped. The below method allows us to identify the view being selected. We can use it, to identify the view from which we would like to hide the touch events or identify the view we are interested into. Example: In the below case when we tap on Black View we can show an alert like "Black View tapped!" , if we tap on Red View , we can show an alert  "You are not allowed to tap on Red View" .  override func hitTest ( _ point: CGPoint , with event: UIEvent ?) -> UIView ? { } Here is a simple implementation of the method, to identify the view being hit. View hierarchy being used is listed below:- Blue(parent) - Red(child) - Green(child) - Yellow (child) - Orange (child) - Black (child) - White (child) So lets' start with override of hitTest method.      override func hitTest ( _ point: CGPoint , with event: UIEvent ?) -> UIView ? {         //1       ...

Understanding Property Wrappers Swift

Property Wrappers Property wrappers in swift help us to separate the code that manages the validation and the code that actually defines it. Code that defines the property var   userId :  Int Code that manages the storage @ UserIdentifier var   userId : Int @ UserIdentifier  is a custom way to manage the storage. Don't worry it will be more clear in some time, but my whole point was to clear the understanding on the difference between defining and managing a property (with the help of Property Wrapper).  Consider a use case of UserIdentifier: We want to have a userId which can take maximum up to 100 ids. If a user tries to set it to a value more than 100, it won't allow Provide a validation flag if value exceeds then 100. i.e true if any adjustments made or else false.  Think of this validation to be added at 5 different properties of different class . It would be very difficult to manage , may be write extension to handle this.  extension Int ...