<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yasir on Medium]]></title>
        <description><![CDATA[Stories by Yasir on Medium]]></description>
        <link>https://medium.com/@thatswiftguy?source=rss-bf2722b71246------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n0Sin-qa9RgOh2v5CFelkA.png</url>
            <title>Stories by Yasir on Medium</title>
            <link>https://medium.com/@thatswiftguy?source=rss-bf2722b71246------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:02:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thatswiftguy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI: 2D Pannable Canvas]]></title>
            <link>https://thatswiftguy.medium.com/swiftui-2d-pannable-canvas-ecadcc0a5d57?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecadcc0a5d57</guid>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 18:17:36 GMT</pubDate>
            <atom:updated>2026-08-10T18:19:58.067Z</atom:updated>
            <content:encoded><![CDATA[<p>I will be sharing, how I built 2D pannable canvas for my one of the SwiftUI app.</p><h3>Goal</h3><p>I will be sharing how I created a realistic 2D canvas for my SwiftUI app <strong>Stone: Habit with Friends &amp; Family,</strong> which I build for #shipaton <a href="https://www.shipaton.com/"><em>hackathon</em></a><em>.</em></p><p>Try now at: <a href="https://testflight.apple.com/join/rHRcTna5"><strong>https://testflight.apple.com/join/rHRcTna5</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p74vZwSlAl39AF8ZfH3wNw.png" /><figcaption>Stone: Habit with Friends &amp; Family</figcaption></figure><h4>Layer 1: Value types (pure geometry, no UIKit)</h4><p><strong>CanvasViewport</strong></p><ul><li>Holds offset (scroll position) + size (screen bounds) → the visible window in world coords.</li><li>rect = whats on screen. cullingRect(margin:) = slightly bigger, so content pops in <em>before</em> the edge instead of snapping.</li></ul><p><strong>CanvasGrid</strong></p><ul><li>Converts abstract Cell(column,row) ↔ world CGPoint. Content is authored in cells; only the grid knows pixels.</li><li>position(of:) returns the cell <strong>center</strong>, matching .position() semantics.</li><li>cell(at:) uses floor, not Int() — truncation-toward-zero would merge -0.4 and 0.4 into one cell and break on negatives.</li></ul><p><strong>PannableCanvasConfiguration</strong></p><ul><li>Every tunable in one struct: worldSize, initialFocus, panStepDistance, minimumPanStepInterval, idleDelay, bounces.</li></ul><h4>Layer 2: The UIKit bridge</h4><p><strong>CanvasScrollView</strong></p><ul><li>3 line UIScrollView subclass exposing an onLayout callbackUIViewRepresentable gives you no hook.</li></ul><p><strong>PannableCanvas2D (the representable)</strong></p><ul><li>Four callbacks out: onViewportChange, onActivityChange, onPanStep, onTouchDown.</li><li>makeUIView setup notes:</li><li>contentInsetAdjustmentBehavior = .never → stops the notch shifting the world down.</li><li>delaysContentTouches = false → buttons respond instantly instead of waiting ~150ms.</li><li>A UILongPressGestureRecognizer with minimumPressDuration = 0 is the trick for a &quot;touch began&quot; callback; cancelsTouchesInView = false so buttons still work.</li><li>Content lives in a UIHostingController whose view is pinned at origin with exactly worldSize → <strong>scroll space == world space</strong>, no coordinate conversion needed.</li></ul><p><strong>Coordinator</strong></p><ul><li>parent is re-seated in updateUIView every render pass — otherwise it holds stale closures.</li><li>configuration is a <em>computed</em> passthrough, so it can never drift from parent.</li><li>sync() guards before assigning contentSize — unconditional assignment triggers layout → update → feedback loop.</li><li><strong>Viewport reporting:</strong> runs 60–120×/sec during a fling; the != dedup guard is load-bearing.</li><li><strong>Activity/idle:</strong> setActive(false) schedules a cancellable DispatchWorkItem; cancelling first makes the timer <em>restart</em> rather than stack up.</li><li><strong>Pan steps (two gates):</strong> must travel panStepDistance <strong>and</strong> respect minimumPanStepInterval, so a fast fling can&#39;t machine-gun haptics. Uses monotonic CACurrentMediaTime(). The anchor is committed only when a step actually fires, so distance suppressed by the time gate stays banked.</li><li>Also re-anchors when <em>not</em> dragging/decelerating (bounce, rotation, programmatic scroll) to avoid spurious steps.</li><li><strong>Centering:</strong> centerSmallContent uses content <em>inset</em> (padding would shift the coordinate system and break grid math); centerIfNeeded runs once via hasCentered, and skips zero-size layout passes so the flag isn&#39;t burned early.</li><li>End-of-scroll is handled in three places (didEndDragging when !decelerate, didEndDecelerating, didEndScrollingAnimation) — miss one and the canvas gets stuck &quot;active&quot;.</li></ul><h4>Layer 3: Content</h4><p><strong>CanvasDotGrid</strong></p><ul><li>1600×2400 @ 50pt = 1,536 dots. As shapes that’s 1,536 view identities; as one Canvas it&#39;s a ~30MB surface at 3×.</li><li>Instead: render <strong>one 50×50 tile</strong> via ImageRenderer, then .resizable(resizingMode: .tile)Core Animation repeats it on the GPU. <strong>Cost is flat regardless of world size.</strong></li><li>Regenerates on displayScale change (external monitor / Catalyst).</li></ul><p><strong>Demo</strong></p><ul><li>Culling: visibleTiles filters by cullingRect()the single biggest win at scale.</li><li>Haptic tick wired to panStepDistance = grid.spacing → one click per grid line.</li><li>The .frame(width:height:) on the ZStack is <strong>required</strong>, else it sizes to content and .position() resolves against the wrong container.</li><li>Custom ButtonStyle uses a spring scale instead of the default opacity fade, which reads as sluggish during a fast pan.</li></ul><h3>Source Code:</h3><pre>import SwiftUI<br>import UIKit<br>import CoreGraphics<br>import QuartzCore<br><br>struct CanvasViewport: Equatable {<br>    var offset: CGPoint = .zero<br>    var size: CGSize = .zero<br><br>    var rect: CGRect {<br>        CGRect(origin: offset, size: size)<br>    }<br><br>    func cullingRect(margin: CGFloat = 200) -&gt; CGRect {<br>        rect.insetBy(dx: -margin, dy: -margin)<br>    }<br>}<br><br>struct CanvasGrid {<br>    struct Cell: Equatable, Hashable {<br>        var column: Int<br>        var row: Int<br><br>        func offset(columns: Int, rows: Int) -&gt; Cell {<br>            Cell(column: column + columns, row: row + rows)<br>        }<br>    }<br><br>    var size: CGSize<br>    var spacing: CGFloat<br><br>    var columns: Int { Int(size.width / spacing) }<br>    var rows: Int { Int(size.height / spacing) }<br><br>    var centerCell: Cell {<br>        Cell(column: columns / 2, row: rows / 2)<br>    }<br><br>    func position(of cell: Cell) -&gt; CGPoint {<br>        CGPoint(x: (CGFloat(cell.column) + 0.5) * spacing,<br>                y: (CGFloat(cell.row) + 0.5) * spacing)<br>    }<br><br>    func cell(at point: CGPoint) -&gt; Cell {<br>        Cell(column: Int(floor(point.x / spacing)),<br>             row: Int(floor(point.y / spacing)))<br>    }<br><br>    func contains(_ cell: Cell) -&gt; Bool {<br>        (0..&lt;columns).contains(cell.column) &amp;&amp; (0..&lt;rows).contains(cell.row)<br>    }<br>}<br><br>struct PannableCanvasConfiguration {<br>    var worldSize: CGSize<br>    var initialFocus: CGPoint?<br>    var panStepDistance: CGFloat = 50<br>    var minimumPanStepInterval: TimeInterval = 0.035<br>    var idleDelay: TimeInterval = 1<br>    var bounces: Bool = false<br><br>    var focus: CGPoint {<br>        initialFocus ?? CGPoint(x: worldSize.width / 2, y: worldSize.height / 2)<br>    }<br>}<br><br>final class CanvasScrollView: UIScrollView {<br>    var onLayout: (() -&gt; Void)?<br><br>    override func layoutSubviews() {<br>        super.layoutSubviews()<br>        onLayout?()<br>    }<br>}<br><br>struct PannableCanvas2D&lt;Content: View&gt;: UIViewRepresentable {<br>    var configuration: PannableCanvasConfiguration<br>    var onViewportChange: (CanvasViewport) -&gt; Void = { _ in }<br>    var onActivityChange: (Bool) -&gt; Void = { _ in }<br>    var onPanStep: () -&gt; Void = {}<br>    var onTouchDown: (CGPoint) -&gt; Void = { _ in }<br>    @ViewBuilder var content: Content<br><br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(parent: self)<br>    }<br><br>    func makeUIView(context: Context) -&gt; CanvasScrollView {<br>        let coordinator = context.coordinator<br><br>        let scrollView = CanvasScrollView()<br>        scrollView.bounces = configuration.bounces<br>        scrollView.showsVerticalScrollIndicator = false<br>        scrollView.showsHorizontalScrollIndicator = false<br>        scrollView.contentInsetAdjustmentBehavior = .never<br>        scrollView.delaysContentTouches = false<br>        scrollView.delegate = coordinator<br>        scrollView.backgroundColor = .clear<br>        scrollView.contentSize = configuration.worldSize<br><br>        let touchDown = UILongPressGestureRecognizer(<br>            target: coordinator,<br>            action: #selector(Coordinator.handleTouchDown)<br>        )<br>        touchDown.minimumPressDuration = 0<br>        touchDown.cancelsTouchesInView = false<br>        touchDown.delaysTouchesBegan = false<br>        touchDown.delegate = coordinator<br>        scrollView.addGestureRecognizer(touchDown)<br><br>        let hostView = coordinator.host.view!<br>        hostView.backgroundColor = .clear<br>        hostView.frame = CGRect(origin: .zero, size: configuration.worldSize)<br>        scrollView.addSubview(hostView)<br><br>        scrollView.onLayout = { [weak scrollView, weak coordinator] in<br>            guard let scrollView, let coordinator else { return }<br>            coordinator.layoutDidChange(scrollView)<br>        }<br><br>        return scrollView<br>    }<br><br>    func updateUIView(_ scrollView: CanvasScrollView, context: Context) {<br>        context.coordinator.parent = self<br>        context.coordinator.host.rootView = content<br>        context.coordinator.sync(scrollView)<br>    }<br><br>    final class Coordinator: NSObject, UIScrollViewDelegate, UIGestureRecognizerDelegate {<br>        var parent: PannableCanvas2D<br>        let host: UIHostingController&lt;Content&gt;<br><br>        private var lastReported = CanvasViewport()<br>        private var pendingIdle: DispatchWorkItem?<br>        private var hasCentered = false<br>        private var panAnchor: CGPoint = .zero<br>        private var lastPanTick: TimeInterval = 0<br><br>        private var configuration: PannableCanvasConfiguration { parent.configuration }<br><br>        init(parent: PannableCanvas2D) {<br>            self.parent = parent<br>            self.host = UIHostingController(rootView: parent.content)<br>            super.init()<br>            host.view.backgroundColor = .clear<br>            host.view.insetsLayoutMarginsFromSafeArea = false<br>        }<br><br>        func sync(_ scrollView: CanvasScrollView) {<br>            guard scrollView.contentSize != configuration.worldSize else { return }<br>            scrollView.contentSize = configuration.worldSize<br>            host.view.frame = CGRect(origin: .zero, size: configuration.worldSize)<br>        }<br>     <br>        func layoutDidChange(_ scrollView: UIScrollView) {<br>            centerSmallContent(scrollView)<br>            centerIfNeeded(scrollView)<br>            reportViewport(scrollView)<br>        }<br><br>        func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>            reportViewport(scrollView)<br>            trackPanSteps(scrollView)<br>        }<br><br>        func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {<br>            setActive(true)<br>        }<br><br>        func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {<br>            if !decelerate { setActive(false) }<br>        }<br><br>        func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {<br>            setActive(false)<br>        }<br><br>        func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {<br>            setActive(false)<br>        }<br><br>        private func reportViewport(_ scrollView: UIScrollView) {<br>            let viewport = CanvasViewport(offset: scrollView.contentOffset,<br>                                          size: scrollView.bounds.size)<br>            guard viewport != lastReported else { return }<br>            lastReported = viewport<br>            parent.onViewportChange(viewport)<br>        }<br><br>        private func setActive(_ active: Bool) {<br>            pendingIdle?.cancel()<br>            pendingIdle = nil<br><br>            guard !active else {<br>                parent.onActivityChange(true)<br>                return<br>            }<br><br>            let idle = DispatchWorkItem { [weak self] in self?.parent.onActivityChange(false) }<br>            pendingIdle = idle<br>            DispatchQueue.main.asyncAfter(deadline: .now() + configuration.idleDelay,<br>                                          execute: idle)<br>        }<br><br>        private func trackPanSteps(_ scrollView: UIScrollView) {<br>            guard scrollView.isDragging || scrollView.isDecelerating else {<br>                panAnchor = scrollView.contentOffset<br>                return<br>            }<br><br>            let offset = scrollView.contentOffset<br>            let travelled = hypot(offset.x - panAnchor.x, offset.y - panAnchor.y)<br>            guard travelled &gt;= configuration.panStepDistance else { return }<br><br>            let now = CACurrentMediaTime()<br>            guard now - lastPanTick &gt;= configuration.minimumPanStepInterval else { return }<br><br>            panAnchor = offset<br>            lastPanTick = now<br>            parent.onPanStep()<br>        }<br><br>        func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,<br>                               shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -&gt; Bool {<br>            true<br>        }<br><br>        @objc func handleTouchDown(_ recognizer: UILongPressGestureRecognizer) {<br>            guard recognizer.state == .began, let canvas = recognizer.view else { return }<br>            parent.onTouchDown(recognizer.location(in: canvas))<br>        }<br>        <br>        private func centerSmallContent(_ scrollView: UIScrollView) {<br>            let bounds = scrollView.bounds.size<br>            let content = scrollView.contentSize<br>            let insetX = max(0, (bounds.width - content.width) / 2)<br>            let insetY = max(0, (bounds.height - content.height) / 2)<br>            let inset = UIEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX)<br>            if scrollView.contentInset != inset { scrollView.contentInset = inset }<br>        }<br><br>        private func centerIfNeeded(_ scrollView: UIScrollView) {<br>            guard !hasCentered else { return }<br>            let bounds = scrollView.bounds.size<br>            let content = scrollView.contentSize<br>            guard bounds.width &gt; 0, bounds.height &gt; 0,<br>                  content.width &gt;= bounds.width, content.height &gt;= bounds.height else { return }<br><br>            hasCentered = true<br>            scrollView.contentOffset = CGPoint(<br>                x: min(max(configuration.focus.x - bounds.width / 2, 0),<br>                       content.width - bounds.width),<br>                y: min(max(configuration.focus.y - bounds.height / 2, 0),<br>                       content.height - bounds.height)<br>            )<br>        }<br>    }<br>}<br><br><br>struct CanvasDotGrid: View {<br>    var spacing: CGFloat = 50<br>    var radius: CGFloat = 1<br>    var color: Color = .white.opacity(0.35)<br><br>    @Environment(\.displayScale) private var displayScale<br>    @State private var tile: Image?<br><br>    var body: some View {<br>        Rectangle()<br>            .fill(.clear)<br>            .overlay { tile?.resizable(resizingMode: .tile) }<br>            .onAppear { if tile == nil { tile = makeTile(scale: displayScale) } }<br>            .onChange(of: displayScale) { _, newScale in<br>                tile = makeTile(scale: newScale)<br>            }<br>    }<br><br>    private func makeTile(scale: CGFloat) -&gt; Image? {<br>        let renderer = ImageRenderer(content:<br>            Canvas { context, _ in<br>                let dot = CGRect(x: spacing / 2 - radius,<br>                                 y: spacing / 2 - radius,<br>                                 width: radius * 2,<br>                                 height: radius * 2)<br>                context.fill(Path(ellipseIn: dot), with: .color(color))<br>            }<br>            .frame(width: spacing, height: spacing)<br>        )<br>        renderer.scale = scale<br>        return renderer.uiImage.map(Image.init(uiImage:))<br>    }<br>}<br><br>private struct DemoTile: Identifiable {<br>    let id = UUID()<br>    var cell: CanvasGrid.Cell<br>    var color: Color<br>    var taps = 0<br>}<br><br>struct PannableCanvas2DDemo: View {<br>    private static let grid = CanvasGrid(size: CGSize(width: 1600, height: 2400),<br>                                         spacing: 50)<br><br>    private static let startingTiles: [DemoTile] = {<br>        let center = grid.centerCell<br>        let colors: [Color] = [.orange, .cyan, .mint, .purple, .pink, .yellow]<br>        let places = [(-1, -1), (0, -1), (1, 0), (-1, 1), (0, 2), (2, 1)]<br>        return zip(colors, places).map { color, place in<br>            DemoTile(cell: center.offset(columns: place.0, rows: place.1), color: color)<br>        }<br>    }()<br><br>    @State private var tiles = PannableCanvas2DDemo.startingTiles<br>    @State private var isPanning = false<br>    @State private var viewport = CanvasViewport()<br><br>    private let haptics = UIImpactFeedbackGenerator(style: .light)<br><br>    private var configuration: PannableCanvasConfiguration {<br>        var configuration = PannableCanvasConfiguration(worldSize: Self.grid.size)<br>        configuration.panStepDistance = Self.grid.spacing<br>        return configuration<br>    }<br><br>    private var visibleTiles: [DemoTile] {<br>        let rect = viewport.cullingRect()<br>        return tiles.filter { rect.contains(Self.grid.position(of: $0.cell)) }<br>    }<br><br>    var body: some View {<br>        PannableCanvas2D(<br>            configuration: configuration,<br>            onViewportChange: { viewport = $0 },<br>            onActivityChange: { isPanning = $0 },<br>            onPanStep: { haptics.impactOccurred(intensity: 0.4) },<br>            onTouchDown: { point in<br>                let cell = Self.grid.cell(at: point)<br>                print(&quot;touched cell \(cell.column), \(cell.row)&quot;)<br>            }<br>        ) {<br>            ZStack(alignment: .topLeading) {<br>                CanvasDotGrid(spacing: Self.grid.spacing)<br><br>                ForEach(visibleTiles) { tile in<br>                    if let index = tiles.firstIndex(where: { $0.id == tile.id }) {<br>                        tileView($tiles[index])<br>                    }<br>                }<br>            }<br>            .frame(width: Self.grid.size.width, height: Self.grid.size.height)<br>            .background(Color.black)<br>        }<br>        .ignoresSafeArea()<br>        .background(Color.black)<br>        .preferredColorScheme(.dark)<br>        .onAppear { haptics.prepare() }<br>        .overlay(alignment: .top) {<br>            Text(&quot;Pannable canvas&quot;)<br>                .font(.footnote.weight(.medium))<br>                .padding(.top, 60)<br>                .opacity(isPanning ? 0 : 1)<br>                .animation(.easeOut(duration: 0.25), value: isPanning)<br>        }<br>    }<br><br>    private func tileView(_ tile: Binding&lt;DemoTile&gt;) -&gt; some View {<br>        Button {<br>            tile.wrappedValue.taps += 1<br>        } label: {<br>            RoundedRectangle(cornerRadius: 9, style: .continuous)<br>                .fill(tile.wrappedValue.color)<br>                .overlay {<br>                    Text(&quot;\(tile.wrappedValue.taps)&quot;)<br>                        .font(.system(size: 15, weight: .bold, design: .rounded))<br>                        .foregroundStyle(.black.opacity(0.55))<br>                }<br>                .frame(width: 36, height: 36)<br>        }<br>        .buttonStyle(DemoTileStyle())<br>        .position(Self.grid.position(of: tile.wrappedValue.cell))<br>    }<br>}<br><br>private struct DemoTileStyle: ButtonStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .scaleEffect(configuration.isPressed ? 0.88 : 1)<br>            .animation(.spring(response: 0.2, dampingFraction: 0.8),<br>                       value: configuration.isPressed)<br>    }<br>}<br><br>#Preview(&quot;Pannable canvas&quot;) {<br>    PannableCanvas2DDemo()<br>}</pre><h3>That’s it!</h3><p>Let’s connect on <a href="https://x.com/thatswiftguy0"><em>twitter</em></a> and <a href="https://www.linkedin.com/in/thatswiftguy/"><em>linkedin</em></a>, cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecadcc0a5d57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styling Custom Views in SwiftUI]]></title>
            <link>https://thatswiftguy.medium.com/styling-custom-views-in-swiftui-cd67f01a0431?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd67f01a0431</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[swifui]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 12:02:05 GMT</pubDate>
            <atom:updated>2025-01-06T12:02:05.192Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll see an example of designing a flexible system for custom views with customizable styles using protocols, environment keys, and view modifiers.</p><p>Goal:</p><blockquote><strong><em>Writing different styles that can be applied to a card view containing only text. We have followed the practices that built-in styling in SwiftUI follows for button styles, menu styles, progress styles, etc.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhKnsJJGzOR8DCq62qxO9A.png" /></figure><p>Steps:</p><ol><li>Create a View Style Protocol</li><li>Create a Style Configuration</li><li>Define New Styles</li><li>Setup the Style Environment</li><li>Add a View Modifier for Styles</li><li>Create a Card View</li><li>Preview with New Styles</li></ol><h3>1. Create a View Style Protocol</h3><p>The foundation of our approach is a CardStyle protocol that defines how to construct a styled card. Here’s the protocol:</p><pre>protocol CardStyle {<br>    associatedtype Body: View<br>    typealias Configuration = CardStyleConfiguration<br><br>    func makeBody(configuration: Self.Configuration) -&gt; Self.Body<br>}</pre><p>The protocol uses an associated type to allow for flexibility in the returned View. The makeBody(configuration:) method generates the styled view based on the provided configuration.</p><h3>2. Create a Style Configuration</h3><p>To enable flexibility, we define a CardStyleConfiguration. It encapsulates the content of the card:</p><pre>struct CardStyleConfiguration {<br>    struct Label: View {<br>        init&lt;Content: View&gt;(content: Content) {<br>            body = AnyView(content)<br>        }<br>        var body: AnyView<br>    }<br><br>    let label: CardStyleConfiguration.Label<br>}</pre><p>The Label struct wraps the card’s content, enabling any view to be used as the label.</p><h3>3. Define New Styles</h3><p>Using the CardStyle protocol, we define several styles:</p><h4>Wave Card Style</h4><pre>struct WaveCardStyle: CardStyle {<br>    var color: Color<br><br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .font(.headline)<br>            .padding()<br>            .background(<br>                ZStack {<br>                    color.opacity(0.6).blur(radius: 10)<br>                    color.opacity(0.4)<br>                        .clipShape(RoundedRectangle(cornerRadius: 30))<br>                }<br>            )<br>            .clipShape(RoundedRectangle(cornerRadius: 20))<br>    }<br>}</pre><h4>Dotted Border Style</h4><pre>struct DottedBorderStyle: CardStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .font(.body)<br>            .padding()<br>            .background(<br>                RoundedRectangle(cornerRadius: 16)<br>                    .strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [5]))<br>                    .foregroundColor(.blue)<br>            )<br>    }<br>}</pre><h4>Default Style</h4><pre>struct DefaultCardStyle: CardStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .font(.title2)<br>            .padding()<br>            .background(Color.gray.opacity(0.2))<br>            .cornerRadius(12)<br>    }<br>}</pre><h3>4. Setup the Style Environment</h3><p>To make the styles dynamic, we use an environment key:</p><pre>struct AnyCardStyle: CardStyle {<br>    private var _makeBody: (Configuration) -&gt; AnyView<br><br>    init&lt;S: CardStyle&gt;(style: S) {<br>        _makeBody = { configuration in<br>            AnyView(style.makeBody(configuration: configuration))<br>        }<br>    }<br><br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        _makeBody(configuration)<br>    }<br>}<br><br>struct CardStyleKey: EnvironmentKey {<br>    static let defaultValue = AnyCardStyle(style: DefaultCardStyle())<br>}<br><br>extension EnvironmentValues {<br>    var cardStyle: AnyCardStyle {<br>        get { self[CardStyleKey.self] }<br>        set { self[CardStyleKey.self] = newValue }<br>    }<br>}</pre><h3>5. Add a View Modifier for Styles</h3><p>The following modifier simplifies applying a custom style to any card:</p><pre>extension View {<br>    func cardStyle&lt;S: CardStyle&gt;(_ style: S) -&gt; some View {<br>        environment(\.[cardStyle], AnyCardStyle(style: style))<br>    }<br>}</pre><h3>6. Create a Card View</h3><p>The Card view dynamically adopts the style from the environment:</p><pre>struct Card&lt;Content: View&gt;: View {<br>    @Environment(\.cardStyle) private var style<br>    var content: () -&gt; Content<br><br>    var body: some View {<br>        style.makeBody(configuration: CardStyleConfiguration(label: CardStyleConfiguration.Label(content: content())))<br>    }<br>}</pre><h3>7. Preview with New Styles</h3><p>Here’s how to use the custom styles in a sample view:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            Card {<br>                Text(&quot;Wave Style&quot;)<br>            }<br>            .cardStyle(WaveCardStyle(color: .blue))<br><br>            Card {<br>                Text(&quot;Dotted Border Style&quot;)<br>            }<br>            .cardStyle(DottedBorderStyle())<br><br>            Card {<br>                Text(&quot;Default Style&quot;)<br>            }<br>        }<br>        .padding()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p>I hope you found it helpful. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd67f01a0431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Perform an Action in the Killed State in iOS Using Swift?]]></title>
            <link>https://blog.stackademic.com/how-to-perform-an-action-in-killed-state-in-ios-using-swift-6a1aaf3d888c?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1aaf3d888c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 12:49:24 GMT</pubDate>
            <atom:updated>2023-08-21T14:36:23.921Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s discuss about it and figure out the solutions for this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYgaITiNSsB3qrFo4JNgow.png" /></figure><h4>Limitations</h4><p>Apple does’t allow you to perform any action in killed state.</p><h4>Solution</h4><p>You can make the app <strong>awake</strong> from <strong>killed</strong> state to <strong>background</strong> state and perform a given task for duration of <strong>30 seconds</strong>.</p><p>To make your app available in <strong>background state</strong> from <strong>killed state</strong>, you will need to setup a <strong>silent push notification</strong>.</p><h4>Silent Push Notification</h4><p>These are the benefits of using silent push notification:</p><ul><li><strong>No visible content</strong>: They don’t display alerts, badges, or sounds to the user.</li><li><strong>Custom data</strong>: They carry specific information or instructions for your app to process in their payload file.</li><li><strong>Wake-up capability</strong>: They can wake up your app from the background or terminated state to perform background tasks or update content without user interaction.</li><li><strong>Server-side implementation</strong>: Your server must be configured to send silent push notifications with the necessary data payload.</li><li><strong>Use cases:</strong> They are commonly used for content updates, data synchronization, and background tasks.</li></ul><blockquote>Now the solution is clear. We will fire a silent push notification and wakes up the app, then we will perform a desired task.</blockquote><p>We will be using firebase to help us with notification. <a href="https://designcode.io/swiftui-advanced-handbook-push-notifications-part-1/">How to setup firebase notification in iOS?</a></p><ol><li><strong>Firebase Cloud Messaging</strong>: Go to firebase -&gt; project setting -&gt; Cloud Messaging. Click on three dot on the right side and open up the “Manage API in google cloud console” and enable the setting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*hkb5TLPcjwvBUicyYQ2Wog.png" /></figure><p><strong>2. Server key:</strong> This setting will give you a <strong>server key. </strong>Go to firebase -&gt; project setting -&gt; Cloud Messaging and copy the <strong>server key.</strong></p><p><strong>3. CURL request: </strong>Modify the following CURL request, replacing placeholders with your server key and device token. (make sure server key starts with “<strong>key=</strong>”).</p><pre>curl -i -X POST \<br>   -H &quot;Content-Type:application/json&quot; \<br>   -H &quot;Authorization:key=YOUR-SERVER-KEY&quot; \<br>   -d \<br>&#39;{<br>  &quot;to&quot;: &quot;YOUR-DEVICE-TOKEN&quot;,<br>  &quot;content_available&quot;: true,<br>  &quot;apns-priority&quot;: 5,<br>  &quot;data&quot;: {<br>    &quot;someData&quot;: &quot;test2222&quot;<br>  }<br>}&#39; \<br> &#39;https://fcm.googleapis.com/fcm/send&#39;</pre><p><strong>4. Handling:</strong> Implement the didReceiveRemoteNotification function in your app&#39;s delegate. Execute desired tasks here.</p><pre>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {<br>  // Once task is finished, call this completion<br>  completionHandler(UIBackgroundFetchResult.newData)<br>}</pre><p><strong>5. Testing:</strong> Now copy this curl and paste it in POST man OR you can use <a href="https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm">this chrome extension.</a></p><ul><li>Make sure <strong>background fetch</strong> and <strong>remote notification</strong> is enabled from your xcode capability settings.</li><li>You can use user default to save some data to test it out. Now fire the curl request. After triggering it, you will be able to save the data even when app is in killed state.</li></ul><h4>Code snippets to help you with integration</h4><ul><li>App delegate</li></ul><pre>@main<br>class AppDelegate: NSObject, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {<br>    let gcmMessageIDKey = &quot;gcm.message_id&quot;<br>    <br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>        FirebaseApp.configure()<br>        Messaging.messaging().delegate = self<br>        <br>        UNUserNotificationCenter.current().delegate = self<br>        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }<br>        <br>        application.registerForRemoteNotifications()<br>        return true<br>    }<br>    <br>    <br>    <br>    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) {<br>        UserDefaults.standard.set(&quot;John&quot;, forKey: &quot;name&quot;)<br>    <br>        if let some = userInfo[&quot;someData&quot;] as? String {<br>            print(&quot;Some data from notification: \(some)&quot;)<br>        }<br>    <br>        if let messageID = userInfo[gcmMessageIDKey] {<br>            print(&quot;Message ID: \(messageID)&quot;)<br>        }<br>    <br>        print(userInfo)<br><br>        completionHandler(UIBackgroundFetchResult.newData)<br>     }<br>    <br>    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {<br>        let deviceToken: [String : String] = [&quot;token&quot; : fcmToken ?? &quot;&quot;]<br>        print(&quot;Device Token: \(deviceToken)&quot;)<br>    }<br>    <br>}</pre><ul><li>Printing the name on launch of application to check if it got saved.</li></ul><pre>class ViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        <br>        print(&quot;name: \(UserDefaults.standard.string(forKey: &quot;name&quot;))&quot;)<br>    }<br>}</pre><h3>That’s it</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9nABcoXr2lqUM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F9nABcoXr2lqUM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F9nABcoXr2lqUM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="318" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f078eb7a75313989fd884635f3cd37/href">https://medium.com/media/71f078eb7a75313989fd884635f3cd37/href</a></iframe><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1aaf3d888c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-perform-an-action-in-killed-state-in-ios-using-swift-6a1aaf3d888c">How to Perform an Action in the Killed State in iOS Using Swift?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[150 Swift Productivity Methods To Use]]></title>
            <link>https://thatswiftguy.medium.com/150-swift-productivity-methods-to-use-97c6b265894?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/97c6b265894</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 10:43:46 GMT</pubDate>
            <atom:updated>2023-06-06T10:43:46.676Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s a collection of 150 swift functional methods with a short description about them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLV3M9DK5KpgksWHVsGGaw.png" /></figure><ol><li>map: Transforms each element in a collection and returns an array containing the results.</li><li>flatMap (or compactMap in Swift 5.0 and later): Transforms each element in a collection and flattens the results into a single-level array.</li><li>filter: Returns a new array containing only the elements that satisfy a given condition.</li><li>reduce: Combines all elements in a collection into a single value by applying a combining closure.</li><li>forEach: Performs a given operation on each element in a collection.</li><li>sort (or sorted): Returns a new array with the elements sorted according to a given closure.</li><li>contains: Checks if a collection contains an element that satisfies a given condition.</li><li>allSatisfy: Checks if all elements in a collection satisfy a given condition.</li><li>anySatisfy: Checks if any element in a collection satisfies a given condition.</li><li>first(where:): Returns the first element in a collection that satisfies a given condition.</li><li>compactMap (or flatMap in Swift 4.2 and earlier): Transforms each element in a collection and removes any nil values from the results.</li><li>split: Splits a collection into multiple subcollections based on a given condition.</li><li>joined: Returns a string by concatenating the elements of a collection into a single string.</li><li>prefix: Returns a subcollection containing the specified number of elements from the start of the collection.</li><li>suffix: Returns a subcollection containing the specified number of elements from the end of the collection.</li><li>drop: Returns a subcollection by omitting the specified number of elements from the start of the collection.</li><li>compactMapValues: Transforms the values of a dictionary and removes any nil values from the results.</li><li>Certainly! Here are a few more higher-order functions available in Swift for working with collections:</li><li>drop(while:): Returns a subcollection by omitting elements from the start of the collection until a condition is no longer satisfied.</li><li>prefix(while:): Returns a subcollection by taking elements from the start of the collection until a condition is no longer satisfied.</li><li>enumerated: Returns a sequence of pairs (index, element) for each element in a collection.</li><li>reversed: Returns a new collection with the elements in reverse order.</li><li>min(by:): Returns the minimum element in a collection based on a given closure.</li><li>max(by:): Returns the maximum element in a collection based on a given closure.</li><li>shuffle: Returns a new collection with the elements shuffled randomly.</li><li>partition(by:): Reorders the elements of a collection so that all elements satisfying a given condition are true to the left of those that don&#39;t.</li><li>contains(where:): Checks if a collection contains an element that satisfies a given condition.</li><li>firstIndex(where:): Returns the index of the first element that satisfies a given condition.</li><li>lastIndex(where:): Returns the index of the last element that satisfies a given condition.</li><li>reduce(into:_:): Combines all elements in a collection into a single value by applying a closure that can mutate an accumulator.</li><li>forEachIndex: Performs a given operation on each element in a collection along with its corresponding index.</li><li>zip: Creates a sequence of pairs by combining elements from two collections.</li><li>compactMapUnique: Transforms elements in a collection and removes any duplicate values from the results.</li><li>reduce(intoResult:_:): Combines all elements in a collection into a single result value by applying a closure that can mutate the result.</li><li>indices: Returns a range of all the valid indices for a collection.</li><li>first: Returns the first element in a collection, or nil if the collection is empty.</li><li>last: Returns the last element in a collection, or nil if the collection is empty.</li><li>first(where:): Returns the first element in a collection that satisfies a given condition.</li><li>last(where:): Returns the last element in a collection that satisfies a given condition.</li><li>single(where:): Returns the single element in a collection that satisfies a given condition, or nil if there are zero or more than one such element.</li><li>dropLast: Returns a subcollection by omitting the specified number of elements from the end of the collection.</li><li>prefix(upTo:): Returns a subcollection containing all the elements from the start of the collection up to, but not including, the specified index.</li><li>suffix(from:): Returns a subcollection containing all the elements from the specified index to the end of the collection.</li><li>reduce(into:combine:): Combines all elements in a collection into a single value using a closure that can mutate an accumulator.</li><li>reduce(_:combine:): Combines all elements in a collection into a single value using a closure.</li><li>forEach(_:do:): Performs a given operation on each element in a collection while passing in the index of each element.</li><li>contains(_:equatable:): Checks if a collection contains a specific element based on equatability.</li><li>allSatisfy(_:predicate:): Checks if all elements in a collection satisfy a given predicate.</li><li>partition(_:isIncluded:): Reorders the elements of a collection based on a predicate, so that all elements satisfying the predicate come before the ones that don&#39;t.</li><li>firstIndex(of:): Returns the index of the first occurrence of a given element in a collection, or nil if the element is not found.</li><li>lastIndex(of:): Returns the index of the last occurrence of a given element in a collection, or nil if the element is not found.</li><li>dropFirst: Returns a subcollection by omitting the specified number of elements from the start of the collection.</li><li>prefix(through:): Returns a subcollection containing all the elements from the start of the collection up to and including the specified index.</li><li>suffix(through:): Returns a subcollection containing all the elements from the specified index to the end of the collection, inclusive.</li><li>partitioned(by:): Splits a collection into two subcollections based on a given predicate, with elements satisfying the predicate in one subcollection and the rest in the other.</li><li>min(): Returns the minimum element in a collection of comparable elements.</li><li>max(): Returns the maximum element in a collection of comparable elements.</li><li>reversed(): Returns a new collection with the elements in reverse order.</li><li>allSatisfy(_:contains:): Checks if all elements in a collection satisfy a given condition by using the contains function.</li><li>forEach(_:index:do:): Performs a given operation on each element in a collection while passing in both the element and its index.</li><li>firstIndex(of:where:): Returns the index of the first occurrence of a given element that satisfies a given condition in a collection, or nil if the element is not found.</li><li>lastIndex(of:where:): Returns the index of the last occurrence of a given element that satisfies a given condition in a collection, or nil if the element is not found.</li><li>split(separator:maxSplits:omittingEmptySubsequences:): Splits a collection into subcollections based on a separator element and a maximum number of splits, optionally omitting empty subsequences.</li><li>joined(separator:): Returns a string by concatenating the elements of a collection into a single string, separated by a given separator.</li><li>lazy: Creates a lazy sequence that defers the execution of transformations until they are actually needed.</li><li>firstIndex(_:in:): Returns the index of the first occurrence of any element in a given set of elements within a collection, or nil if none of the elements are found.</li><li>indices(where:): Returns a sequence of indices for elements in a collection that satisfy a given predicate.</li><li>prefix(while:): Returns a subcollection containing elements from the start of the collection until a condition is no longer satisfied.</li><li>suffix(while:): Returns a subcollection containing elements from the end of the collection until a condition is no longer satisfied.</li><li>reduce(into:while:): Combines elements in a collection into a single value using a closure that can mutate an accumulator until a condition is no longer satisfied.</li><li>forEachSlice(size:do:): Performs a given operation on each slice of elements in a collection with a specified size.</li><li>compactMapUniqueValues: Transforms values in a dictionary and removes any duplicate values from the results.</li><li>stride(from:to:by:): Returns a sequence of values starting from a given value, up to, but not including, a specified end value, with a specified step.</li><li>stride(from:through:by:): Returns a sequence of values starting from a given value, up to and including a specified end value, with a specified step.</li><li>forEachChunk(size:do:): Performs a given operation on each chunk of elements in a collection with a specified size.</li><li>partitionAll(by:): Splits a collection into subcollections based on a given predicate, with each subcollection containing consecutive elements that satisfy the predicate.</li><li>filtering(_:isIncluded:): Filters a collection by including only the elements that satisfy a given condition, and removes the rest.</li><li>splitOnce(separator:): Splits a collection into two subcollections based on the first occurrence of a separator element.</li><li>reduceRight(into:combine:): Combines elements in a collection into a single value from right to left using a closure that can mutate an accumulator.</li><li>forEachIndexOffset(size:do:): Performs a given operation on each element in a collection along with its index and offset from the start.</li><li>cycled(): Returns a new collection that cycles through the elements of the original collection indefinitely.</li><li>grouped(by:): Groups elements in a collection into a dictionary based on a given closure, with the closure&#39;s result as the key and the elements as the values.</li><li>scan(_:_:): Applies a closure to each element in a collection, accumulating the results, and returns an array of the intermediate values.</li><li>zip(_: _: _: _:): Creates a sequence of tuples by combining elements from four collections.</li><li>lazyMap(_:): Creates a lazy sequence by applying a transformation to each element in a collection.</li><li>interleave(_: _: _: _:): Creates a sequence by interleaving elements from four collections.</li><li>indexed(): Returns a sequence of tuples containing the index and element for each element in a collection.</li><li>unzip(_:): Separates an array of tuples into separate arrays, each containing elements at a specific position.</li><li>scan(into:_:): Applies a closure to each element in a collection, accumulating the results into an array.</li><li>rotate(shiftingToStart:): Returns a new collection with the elements rotated by a specified number of positions.</li><li>chunked(by:): Groups elements in a collection into subarrays based on a given closure, with the closure&#39;s result determining the grouping.</li><li>noneSatisfy(_:predicate:): Checks if none of the elements in a collection satisfy a given predicate.</li><li>indexedFilter(_:include:): Returns an array of elements from a collection at the specified indices.</li><li>consecutiveGroups(_:areInIncreasingOrder:): Groups consecutive elements in a collection based on a given closure that determines the order.</li><li>forEachOffset(_:do:): Performs a given operation on each element in a collection along with its offset from the start.</li><li>indexedReduce(into:combine:): Combines elements in a collection into a single value using a closure that can mutate an accumulator, with access to the element&#39;s index.</li><li>groupAdjacent(by:): Groups adjacent elements in a collection based on a given closure.</li><li>compactMapFirst(where:): Transforms elements in a collection and returns the first non-nil result that satisfies a given condition.</li><li>interleave(sequence:): Creates a sequence by interleaving elements from a collection with another sequence.</li><li>recurrentReduce(_:_:): Applies a recurrent reduction to a collection, building up an intermediate result with a given closure.</li><li>append(_:while:): Appends elements to a collection until a given condition is no longer satisfied.</li><li>unzip3(_:): Separates an array of triples into three separate arrays, each containing elements at a specific position.</li><li>index(of:in:): Returns the index of the first occurrence of a given element in a collection, or nil if the element is not found.</li><li>containsAll(_:equatable:): Checks if a collection contains all elements from another collection based on equatability.</li><li>firstDuplicate(): Returns the first duplicate element in a collection, or nil if there are no duplicates.</li><li>lazyFilter(_:predicate:): Creates a lazy sequence by filtering elements in a collection based on a given predicate.</li><li>windowed(by:size:step:): Returns a sequence of sliding windows over a collection with a specified size and step.</li><li>take(_:repeating:): Returns a collection by repeating a given element a specified number of times.</li><li>forEachReversed(_:do:): Performs a given operation on each element in a collection in reverse order.</li><li>countOccurrences(of:in:): Returns the number of occurrences of a given element in a collection.</li><li>cycled(by:): Returns a new collection that cycles through the elements of the original collection repeatedly, applying a given closure to each cycle.</li><li>consecutiveReducing(_:initialResult:nextPartialResult:): Applies a reducing closure to consecutive pairs of elements in a collection, accumulating the results.</li><li>forEachSliceIndices(size:do:): Performs a given operation on each slice of elements in a collection with a specified size, passing in both the slice and its indices.</li><li>chunked(by:isEquivalent:): Groups elements in a collection into subarrays based on a given closure that determines the grouping, using a custom equivalence check.</li><li>rotate(shiftingToEnd:): Returns a new collection with the elements rotated by a specified number of positions, in the opposite direction as rotate(shiftingToStart:).</li><li>filterUnique(by:): Filters a collection to include only the unique elements based on a given closure that determines uniqueness.</li><li>lazyEnumerated(): Creates a lazy sequence of tuples containing the index and element for each element in a collection.</li><li>splitAt(index:): Splits a collection into two subcollections at the specified index.</li><li>reduceRight(_:nextPartialResult:combine:): Combines elements in a collection into a single value from right to left using a reducing closure.</li><li>enumerateGroups(_:areEquivalent:): Groups elements in a collection based on a given closure that determines equivalence.</li><li>filtering(_:isIncluded:isExcluded:): Filters a collection by including only the elements that satisfy a given inclusion condition and excluding the elements that satisfy an exclusion condition.</li><li>lastIndexOf(_:in:): Returns the index of the last occurrence of a given element in a collection, or nil if the element is not found.</li><li>chunked(into:): Groups elements in a collection into subarrays with a specified maximum size.</li><li>unwrap(): Returns an array by unwrapping optional elements in a collection and removing any nil values.</li><li>repeatingElements(): Returns a new collection by repeating each element in the original collection a number of times equal to its value.</li><li>forEachPair(_:do:): Performs a given operation on each pair of adjacent elements in a collection.</li><li>chunked(by:isIncluded:): Groups elements in a collection into subarrays based on a given closure that determines the grouping, and includes only the elements that satisfy a condition.</li><li>indexedScan(into:_:): Applies a closure to each element in a collection, accumulating the results into an array, and providing access to the element&#39;s index.</li><li>slice(from:to:): Returns a subsequence of elements from a collection, starting from a given start index and ending before a given end index.</li><li>reduceWhile(_:nextPartialResult:shouldContinue:): Combines elements in a collection into a single value using a reducing closure, until a condition is no longer satisfied.</li><li>takeLast(_:repeating:): Returns a collection by repeating a given element a specified number of times, starting from the end.</li><li>repeatedPermutations(of:count:): Returns a sequence of arrays representing all possible repeated permutations of a collection&#39;s elements, up to a specified count.</li><li>filterDuplicates(): Filters a collection to include only the unique elements, removing any duplicates.</li><li>allEqual(): Checks if all elements in a collection are equal.</li><li>forEachWindow(size:do:): Performs a given operation on each window of elements in a collection with a specified size.</li><li>mapIndexed(_:transform:): Transforms elements in a collection using a closure that receives both the element and its index.</li><li>interpose(element:): Returns a new collection by inserting a given element between every pair of adjacent elements in the original collection.</li><li>concurrentMap(_:_:): Applies a given closure to each element in a collection concurrently, returning an array of the results.</li><li>forEachPermutation(_:do:): Performs a given operation on each permutation of a collection&#39;s elements.</li><li>firstIndex(of:in:where:): Returns the index of the first occurrence of a given element in a collection that satisfies a given condition, or nil if the element is not found.</li><li>groupBy(_:transform:): Groups elements in a collection into a dictionary based on a given closure that determines the key for each element.</li><li>reduceRightWhile(_:nextPartialResult:shouldContinue:): Combines elements in a collection into a single value from right to left using a reducing closure, until a condition is no longer satisfied.</li><li>rotated(by:): Returns a new collection with the elements rotated by a specified number of positions, positive for clockwise rotation and negative for counterclockwise rotation.</li><li>indexedPartition(_:isIncluded:): Partitions a collection into two subcollections based on a given closure, and retains the indices of the original elements.</li><li>reducedValues(): Returns an array of unique values obtained by applying a reducing closure to each element in a collection.</li><li>forEachCombination(ofSize:do:): Performs a given operation on each combination of a specified size from a collection&#39;s elements.</li><li>trimPrefix(_:isEquivalent:): Returns a subcollection by removing elements from the start of a collection that match a given predicate, using a custom equivalence check.</li><li>filterPairs(_:include:): Filters a collection to include only the pairs of adjacent elements that satisfy a given condition.</li><li>unwrapMap&lt;U&gt;(_:_:): Transforms elements in a collection using a closure that unwraps optional elements and maps them to a new type.</li><li>recurrentReduce(into:initialResult:nextPartialResult:): Applies a recurrent reducing closure to a collection, building up an intermediate result with a given closure that can mutate the accumulator.</li><li>flatMapIndexed(_:transform:): Transforms elements in a collection using a closure that receives both the element and its index, and flattens the results.</li></ol><p>I took the help of AI to collect these methods. These methods can make life a lot easier while building an app.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97c6b265894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to download & save the video in device storage in swift]]></title>
            <link>https://thatswiftguy.medium.com/how-to-download-save-the-video-in-device-storage-in-swift-a1129aecd736?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1129aecd736</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 11:50:09 GMT</pubDate>
            <atom:updated>2023-02-05T11:51:06.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Download video with <strong>progress</strong> in swift and <strong>save</strong> it in device permanent storage with an album.</p><p>In this article, we will see how we can download a video using URLSession and get the progress of downloading. And then we will be saving that video in our device permanent storage.</p><p>Also, we will be creating an album where we will be saving all those videos.</p><blockquote><strong>Complete code is available at the end of this article.</strong></blockquote><h3>Are you looking for:</h3><ol><li>How to <strong>download</strong> video with URLSession in swift?</li><li>How to save a video in <strong>device permanent storage </strong>in swift?</li><li>How to save a video in an <strong>album </strong>in device in swift?</li><li>How to get <strong>progress</strong> of video downloading in swift?</li></ol><p>Then, this article is for you.</p><h3>Frameworks &amp; Tools we will use</h3><ul><li>SwiftUI</li><li>URLSession</li><li>Photos</li><li>AVFoundation</li><li>XCode</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHMCaTz8kAB1wshxboIOqw.png" /><figcaption>Article Cover</figcaption></figure><h3>Downloading the video with progress and saving it in device permanent storage with an album</h3><p>Create a viewModel which conforms to protocol URLSessionDownloadDelegate. So that we can track the <strong>progress</strong> &amp; <strong>completion</strong> of downloading.</p><pre>import Foundation<br>import Photos<br>import AVFoundation<br><br>class DownloadViewModel: NSObject, ObservableObject, URLSessionDownloadDelegate {<br>    @Published var progress: Float = 0<br>    <br>    func downloadVideo(url: URL) {<br>        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)<br>        let task = session.dataTask(with: url) { (data, response, error) in<br>            guard error == nil else {<br>                return<br>            }<br>            let downloadTask = session.downloadTask(with: url)<br>            downloadTask.resume()<br>        }<br>        task.resume()<br>    }<br>}</pre><p>Add these functions to conform the protocol in “DownloadViewModel”.</p><ul><li>didFinishDownloadingTo will give the address of downloaded url.</li><li>didWriteData will give the progress of downloading.</li></ul><pre>class DownloadViewModel: NSObject, ObservableObject, URLSessionDownloadDelegate {<br>   <br>    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {<br>        <br>    }<br>    <br>    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {<br>       <br>    }<br>}</pre><p>Now, update the didFinishDownloadingTo function as below.</p><pre>func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {<br>    guard let data = try? Data(contentsOf: location) else {<br>        return<br>    }<br>    <br>    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]<br>    let destinationURL = documentsURL.appendingPathComponent(&quot;myVideo.mp4&quot;)<br>    do {<br>        try data.write(to: destinationURL)<br>        saveVideoToAlbum(videoURL: destinationURL, albumName: &quot;MyAlbum&quot;)<br>    } catch {<br>        print(&quot;Error saving file:&quot;, error)<br>    }<br>}</pre><p>Now, update the didWriteData function also as below.</p><pre>func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {<br>    print(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))<br>    DispatchQueue.main.async {<br>        self.progress = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))<br>    }<br>}</pre><p>As of now, you got the downloaded video with a progress. Now we will saving that video in an album of device permanent storage.</p><p>Add these functions to “DownloadViewModel”.</p><pre>private func saveVideoToAlbum(videoURL: URL, albumName: String) {<br>    if albumExists(albumName: albumName) {<br>        let fetchOptions = PHFetchOptions()<br>        fetchOptions.predicate = NSPredicate(format: &quot;title = %@&quot;, albumName)<br>        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)<br>        if let album = collection.firstObject {<br>            saveVideo(videoURL: videoURL, to: album)<br>        }<br>    } else {<br>        var albumPlaceholder: PHObjectPlaceholder?<br>        PHPhotoLibrary.shared().performChanges({<br>            let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)<br>            albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection<br>        }, completionHandler: { success, error in<br>            if success {<br>                guard let albumPlaceholder = albumPlaceholder else { return }<br>                let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)<br>                guard let album = collectionFetchResult.firstObject else { return }<br>                self.saveVideo(videoURL: videoURL, to: album)<br>            } else {<br>                print(&quot;Error creating album: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>            }<br>        })<br>    }<br>}<br><br>private func albumExists(albumName: String) -&gt; Bool {<br>    let fetchOptions = PHFetchOptions()<br>    fetchOptions.predicate = NSPredicate(format: &quot;title = %@&quot;, albumName)<br>    let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)<br>    return collection.firstObject != nil<br>}<br><br>private func saveVideo(videoURL: URL, to album: PHAssetCollection) {<br>    PHPhotoLibrary.shared().performChanges({<br>        let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)<br>        let albumChangeRequest = PHAssetCollectionChangeRequest(for: album)<br>        let enumeration: NSArray = [assetChangeRequest!.placeholderForCreatedAsset!]<br>        albumChangeRequest?.addAssets(enumeration)<br>    }, completionHandler: { success, error in<br>        if success {<br>            print(&quot;Successfully saved video to album&quot;)<br>        } else {<br>            print(&quot;Error saving video to album: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>        }<br>    })<br>}</pre><p>Make sure that you have added these properties in your info list file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnhekfflQjIm6qgH0ijQDw.png" /><figcaption>Info.plist</figcaption></figure><p>You can try the project. Make sure the video url is mp4 and correct.</p><pre>struct ContentView: View {<br>    @StateObject var viewModel: DownloadViewModel = .init()<br>    <br>    var body: some View {<br>        VStack {<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundColor(.accentColor)<br>            Text(&quot;Progress: \(viewModel.progress)&quot;)<br>            Button {<br>                if let url = URL(string: &quot;http://techslides.com/demos/sample-videos/small.mp4&quot;) {<br>                    viewModel.downloadVideo(url: url)<br>                }<br>            } label: {<br>                Text(&quot;download&quot;)<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p>You might wanted a view model saparatelyl, download manager saparatly and video saver saparatly. And that’s total up to you and your architecture. This article is just to give you the idea.</p><h3><strong>Complete code</strong></h3><pre>import Foundation<br>import SwiftUI<br>import Photos<br>import AVFoundation<br><br>class DownloadViewModel: NSObject, ObservableObject, URLSessionDownloadDelegate {<br>    @Published var progress: Float = 0<br>    <br>    func downloadVideo(url: URL) {<br>        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)<br>        let task = session.dataTask(with: url) { (data, response, error) in<br>            guard error == nil else {<br>                return<br>            }<br>            let downloadTask = session.downloadTask(with: url)<br>            downloadTask.resume()<br>        }<br>        task.resume()<br>    }<br>    <br>    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {<br>        guard let data = try? Data(contentsOf: location) else {<br>            return<br>        }<br>        <br>        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]<br>        let destinationURL = documentsURL.appendingPathComponent(&quot;myVideo.mp4&quot;)<br>        do {<br>            try data.write(to: destinationURL)<br>            saveVideoToAlbum(videoURL: destinationURL, albumName: &quot;MyAlbum&quot;)<br>        } catch {<br>            print(&quot;Error saving file:&quot;, error)<br>        }<br>    }<br>    <br>    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {<br>        print(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))<br>        DispatchQueue.main.async {<br>            self.progress = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))<br>        }<br>    }<br>    <br>    private func saveVideoToAlbum(videoURL: URL, albumName: String) {<br>        if albumExists(albumName: albumName) {<br>            let fetchOptions = PHFetchOptions()<br>            fetchOptions.predicate = NSPredicate(format: &quot;title = %@&quot;, albumName)<br>            let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)<br>            if let album = collection.firstObject {<br>                saveVideo(videoURL: videoURL, to: album)<br>            }<br>        } else {<br>            var albumPlaceholder: PHObjectPlaceholder?<br>            PHPhotoLibrary.shared().performChanges({<br>                let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)<br>                albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection<br>            }, completionHandler: { success, error in<br>                if success {<br>                    guard let albumPlaceholder = albumPlaceholder else { return }<br>                    let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)<br>                    guard let album = collectionFetchResult.firstObject else { return }<br>                    self.saveVideo(videoURL: videoURL, to: album)<br>                } else {<br>                    print(&quot;Error creating album: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>                }<br>            })<br>        }<br>    }<br>    <br>    private func albumExists(albumName: String) -&gt; Bool {<br>        let fetchOptions = PHFetchOptions()<br>        fetchOptions.predicate = NSPredicate(format: &quot;title = %@&quot;, albumName)<br>        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)<br>        return collection.firstObject != nil<br>    }<br>    <br>    private func saveVideo(videoURL: URL, to album: PHAssetCollection) {<br>        PHPhotoLibrary.shared().performChanges({<br>            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)<br>            let albumChangeRequest = PHAssetCollectionChangeRequest(for: album)<br>            let enumeration: NSArray = [assetChangeRequest!.placeholderForCreatedAsset!]<br>            albumChangeRequest?.addAssets(enumeration)<br>        }, completionHandler: { success, error in<br>            if success {<br>                print(&quot;Successfully saved video to album&quot;)<br>            } else {<br>                print(&quot;Error saving video to album: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>            }<br>        })<br>    }<br>}<br><br>struct ContentView: View {<br>    @StateObject var viewModel: DownloadViewModel = .init()<br>    <br>    var body: some View {<br>        VStack {<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundColor(.accentColor)<br>            Text(&quot;Progress: \(viewModel.progress)&quot;)<br>            Button {<br>                if let url = URL(string: &quot;http://techslides.com/demos/sample-videos/small.mp4&quot;) {<br>                    viewModel.downloadVideo(url: url)<br>                }<br>            } label: {<br>                Text(&quot;download&quot;)<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><h3>The End</h3><p>Hope you learned something new from this article.</p><p>You can reach out to me at:</p><ul><li><a href="https://www.linkedin.com/in/my-pro-file/">LinkedIn</a></li><li><a href="https://twitter.com/statoways">Twitter</a></li></ul><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1129aecd736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before the Interview — Cracking the Coding Interview]]></title>
            <link>https://medium.com/thedevproject/before-the-interview-cracking-the-coding-interview-a3b84adc644c?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b84adc644c</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 03:45:22 GMT</pubDate>
            <atom:updated>2022-04-06T03:05:40.631Z</atom:updated>
            <content:encoded><![CDATA[<h3>Before the Interview — Cracking the Coding Interview</h3><p>Few points about the second chapter “Before the Interview” of book “Cracking the Coding Interview”.</p><h3>Reference</h3><p>The chapter “Before the Interview” is picked from Cracking the Coding Interview book written by <a href="https://medium.com/u/e21bc4f4525e">Gayle Laakmann McDowell</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SgoeOFjzZr11voyVrpboGw.png" /></figure><h3>Highlights</h3><ul><li>Acing an interview starts well before the interview itself — years before, in fact.</li></ul><h4>Getting the Right Experience</h4><ul><li>Without a <strong>great resume</strong>, there’s <strong>no interview</strong>. And without <strong>great experience</strong>, there is <strong>no great resume</strong>.</li><li>Getting a great experience is important to land the interview</li></ul><p><strong>For current students, this may mean the following:</strong></p><ul><li><strong>Take the Big Project Classes</strong>: big coding projects, more relevant to real world is better.</li><li><strong>Get an internship</strong>: Do everything you can to land an internship — early in school, if possible.</li><li><strong>Start something</strong>: build something or hackathons, or open source</li></ul><p><strong>For Professionals</strong></p><ul><li>Having a <strong>well known</strong> company experience will <strong>not create</strong> a problem to shift. But if you are <strong>not at well known</strong> company, then following things you can do.</li><li><strong>Shift Work Responsibilities More Towards Coding</strong>: Without revealing to your manager that you are thinking of leaving, you can discuss your eagerness to take on bigger coding challenges.</li><li><strong>Use Your Nights and Weekends</strong>: Build something</li></ul><h4>Writing a Great Resume</h4><ul><li>Resume screeners look for the same things that interviewers do.</li></ul><p><strong>Employment History:</strong></p><p>For each role, try to discuss your <strong>accomplishments</strong> with the following approach: “Accomplished X by imple­menting Y which led to z:· Here’s an example:</p><p>• “Reduced object rendering time by 75% by implementing distributed caching, leading to a 10% reduc­tion in log-in time:·</p><p>Here’s another example with an alternate wording:</p><p>• “Increased average match accuracy from 1.2 to 1.5 by implementing a new comparison algorithm based on windiff.</p><p>Not everything you did will fit into this approach, but the principle is the same: show what you did, how you did it, and what the results were. Ideally, you should try to make the results “measurable” somehow.</p><p><strong>Projects</strong>:</p><ul><li>The projects should include your 2–4 most <strong>significant</strong> projects.</li><li>Do not add <strong>too</strong> many projects.</li></ul><p><strong>Programming languages and softwares:</strong></p><ul><li>Listing everything you’ve ever worked with is <strong>dangerous</strong>. Many interviewers consider anything on your resume to be “fair game” as far as the interview.</li><li>One alternative is to list most of the languages you’ve used, but add your <strong>experience</strong> level. This approach is shown below:</li><li>Languages: Java (expert}, C++ (proficient), JavaScript (prior experience).</li></ul><p><strong>Being Too Language Focused:</strong></p><ul><li>When recruiters at some of the top tech companies see resumes that list every flavor of Java on their resume, they make <strong>negative</strong> assumptions about the caliber of candi­date.</li></ul><p><strong>Knowing Only One or Two Languages:</strong></p><ul><li>The <strong>more time you’ve spent coding</strong>, the<strong> more things you’ve built</strong>, the <strong>more languages</strong> you will have tended to work with.</li><li>The assumption then, when they see a resume with only one language, is that you haven’t experienced <strong>very many problems</strong>.</li></ul><h4>Preparation Map</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*zrlQzVzabFw04iD_1daneg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*SfCbi_O8Ut-Cp0AYUr5tSA.png" /></figure><h3>Note</h3><blockquote><em>It is really not possible to conclude all the points of “Before the Interview” chapter in an article. Reading full chapter is recommended.</em></blockquote><h3>Socials</h3><ul><li>Follow me on <a href="https://twitter.com/mohdYasir03"><strong><em>twitter</em></strong></a>, <a href="https://www.linkedin.com/in/my-pro-file/"><strong><em>linkedIn</em></strong></a>, <a href="https://github.com/myawesomehub"><strong><em>github</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b84adc644c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thedevproject/before-the-interview-cracking-the-coding-interview-a3b84adc644c">Before the Interview — Cracking the Coding Interview</a> was originally published in <a href="https://medium.com/thedevproject">The Dev Project</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Special Situations — Cracking the Coding Interview]]></title>
            <link>https://thatswiftguy.medium.com/special-situations-cracking-the-coding-interview-f6dcaea40894?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6dcaea40894</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 04:02:44 GMT</pubDate>
            <atom:updated>2022-04-06T03:06:15.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>Special Situations — Cracking the Coding Interview</h3><p>Few points about the second chapter “Special Situations” of book “Cracking the Coding Interview”.</p><h3>Reference</h3><p>The chapter “Special Situations” is picked from Cracking the Coding Interview book written by <a href="https://medium.com/u/e21bc4f4525e">Gayle Laakmann McDowell</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JdVBi_Hsas99o5CbxS8hqg.png" /></figure><h3>Highlights</h3><h4>Testers and SDETs</h4><ul><li>SDETs : They have to be <strong>great coders</strong> and <strong>great testers</strong>. <strong>Double</strong> the prep work!</li><li>If you are <strong>hoping</strong> to apply to an SDET position as the “<strong>easy</strong>” way into a company, be <strong>aware</strong> that many candidates find it vary <strong>difficult</strong> to move from as <strong>SDET position to a dev position</strong>.</li></ul><h4>Dev Lead and Managers</h4><ul><li>Dev leads and managers are almost needs <strong>strong</strong> coding and algorithms skills with following</li></ul><ol><li>Team work/ Leaderships</li><li>Communication</li><li>Prioritizations</li><li>Getting things done</li></ol><h4>Startups</h4><ul><li><strong>The application process</strong>: mostly through personal referral</li><li><strong>Visas and Work Authorization</strong>: Unfortunately, many smaller startups in the US are not able to sponsor work visas.</li><li><strong>Resume Selection Factors</strong>: smart + code + entrepreneurial + resume + projects</li><li><strong>The Interview Process</strong>: They likely to assess your skills with specific programming language. And pay special attention to the behavioural questions.</li></ul><ol><li>Personality Fit</li><li>Skill Set</li><li>Experience</li></ol><h3>Note</h3><blockquote><em>It is really not possible to conclude all the points of “</em>Special Situations<em>” chapter in an article. Reading full chapter is recommended.</em></blockquote><h3>Socials</h3><ul><li>Follow me on <a href="https://twitter.com/mohdYasir03"><strong><em>twitter</em></strong></a>, <a href="https://www.linkedin.com/in/my-pro-file/"><strong><em>linkedIn</em></strong></a>, <a href="https://github.com/myawesomehub"><strong><em>github</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6dcaea40894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Interview Process — Cracking the Coding Interview]]></title>
            <link>https://medium.com/theleanprogrammer/the-interview-process-cracking-the-coding-interview-f13e04804e99?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/f13e04804e99</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 02:23:02 GMT</pubDate>
            <atom:updated>2022-04-06T03:07:08.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Interview Process — Cracking the Coding Interview</h3><p>Few points about the first chapter “<strong>The Interview Process</strong>” of book “Cracking the Coding Interview”.</p><h3>Reference</h3><p>The chapter “<strong>The Interview Process</strong>” is picked from <strong>Cracking the Coding Interview</strong> book written by <a href="https://medium.com/u/e21bc4f4525e">Gayle Laakmann McDowell</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zx-dHnGMih1PtMnpJ8L0w.png" /></figure><h3>Highlights</h3><ul><li>The interviewer is looking to <strong>evaluate</strong> your ability to solve algorithmic problems you <strong>haven’t seen before</strong></li><li>Talk out <strong>loud</strong> while discussing about problem</li><li>Interviewer generally make an assessment of your performance based on</li></ul><ol><li>Analytical skills</li><li>Coding skills</li><li>Technical knowledge / CS Fundamentals</li><li>Experience</li><li>Culture fit / Communication</li></ol><ul><li>False <strong>negatives</strong> are <strong>acceptable</strong></li><li>They are far more concerned with <strong>false positives</strong>: people who do well in an interview but <strong>are not</strong> in fact vary good</li><li>Problem solving skills are valuable</li><li>Basic data structure and algorithm knowledge is useful</li><li>Whiteboards let you focus on what matters</li><li>Most interviewers are<strong> not okay</strong> with <strong>pseudocode</strong> AND whiteboard is better with <strong>fewer errors</strong></li><li>There are <strong>no lists</strong> of what interviewer should ask</li><li>Interviewer has a comparison between your assessment with others in mind</li></ul><h3>Note</h3><blockquote>It is really<strong> not possible</strong> to conclude all the points of “The Interview Process” chapter in an article. Read full chapter is recommended.</blockquote><h3>Socials</h3><ul><li>Follow me on <a href="https://twitter.com/mohdYasir03"><strong><em>twitter</em></strong></a>, <a href="https://www.linkedin.com/in/my-pro-file/"><strong><em>linkedIn</em></strong></a>, <a href="https://github.com/myawesomehub"><strong><em>github</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f13e04804e99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/the-interview-process-cracking-the-coding-interview-f13e04804e99">The Interview Process — Cracking the Coding Interview</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion — A Short Note]]></title>
            <link>https://thatswiftguy.medium.com/recursion-a-short-note-b015bbf69558?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/b015bbf69558</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 10:10:51 GMT</pubDate>
            <atom:updated>2021-12-01T10:10:51.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recursion — A Short Note</h3><p>We will look at stack and few things about recursion and then some problems to be practiced.</p><h3>Overview</h3><p>To be honest, recursion is the most important topic over all others. You will be using it for binary search, heap, graphs, reversals, dynamic programming and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qAfG-6HltAZ4BY5c" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Call Stack ?</h3><p>It is a stack that tracks the program executions, also known as <strong>execution stack</strong>, <strong>program stack</strong>, <strong>control stack</strong>, <strong>run-time stack</strong>, or <strong>machine stack</strong>.</p><p>As we call the functions, the call stack arranged the function executions itself and work according to LIFO nature.</p><p><strong>Note: Once the function done their job, it get removed from the call stack.</strong></p><blockquote>How good you are at imagining the call stack is going to give you more control on recursion.</blockquote><h3>Recursion</h3><p>Recursion does not take constant space, because the call stack takes the memory spaces. Which will be O(n) in linear recurrence.</p><p>The recursive solutions look simple but visualization and tracing takes time and space.</p><p>A recurrence is an equation or inequality that describes a function in terms of its values on smaller inputs.</p><p>There are two types of recurrence, <strong>linear </strong>recurrence<strong> </strong>and <strong>divide and conquer </strong>recurrence. The divide and conquer is better than the linear recurrence, because it halfs the area of input to work on, on each recursive calls.</p><p>Linear recurrence : Fibonacci series<br>Divide and conquer recurrence : Binary Search</p><blockquote><strong>While writing recursive functions, make sure to be right at choosing what to be in argument and what should be in functions body.</strong></blockquote><h3>Solving problems on recursion</h3><p>Write the below programs using recursion to get a good control on it.</p><ul><li>Sum of digits with recursion</li><li>Product of digits with recursion</li><li>Reverse a string</li><li>Count zero in number using recursion</li><li>Linear search with recursion</li><li>Binary search with recursion</li><li>Check if array is sorted with recursion</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F13rQ7rrTrvZXlm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F13rQ7rrTrvZXlm%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExemptdnFodGtpM2g4bjNxdTB5MHo3eXZzOGh1c2VqM3ZpNm41bTU1YiZlcD12MV9naWZzX2dpZklkJmN0PWc%2F13rQ7rrTrvZXlm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="289" frameborder="0" scrolling="no"><a href="https://medium.com/media/75dc139e417f5e5745dfbca82c8c2a90/href">https://medium.com/media/75dc139e417f5e5745dfbca82c8c2a90/href</a></iframe><h3>Thanks for Reading 💯</h3><p><a href="https://www.linkedin.com/in/my-pro-file/">LinkedIn</a> — <a href="https://github.com/myawesomehub">GitHub</a></p><p>Sheet : <a href="https://bit.ly/38HOQeb">https://bit.ly/38HOQeb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b015bbf69558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Call in Swift Part 2]]></title>
            <link>https://medium.com/theleanprogrammer/api-call-in-swift-part-2-completion-error-handling-88075bf0210d?source=rss-bf2722b71246------2</link>
            <guid isPermaLink="false">https://medium.com/p/88075bf0210d</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Yasir]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 13:52:42 GMT</pubDate>
            <atom:updated>2021-09-04T14:59:23.054Z</atom:updated>
            <content:encoded><![CDATA[<h4>Completion and Error Handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbHpKY85pJYpF_BRb73vdw.png" /></figure><p><strong>Improving network call from </strong><a href="https://mdcode2021.medium.com/api-call-in-swift-part-1-urlsession-c013fd9e575f"><strong>part 1</strong></a><strong>. Using completions and error handlings.</strong></p><p>In part 1, we saw how to make a network or API call in a very basics way. But in this article, we will try to improve a bit the code. We will use some completions, error handling, and a proper view model.</p><p>Again, we are not going to use any third party. We will be using all the apple APIs.</p><p>I am not showing the decodable model, because it&#39;s similar to what it was in <a href="https://mdcode2021.medium.com/api-call-in-swift-part-1-urlsession-c013fd9e575f">part 1</a>. If you wish to see it, you can refer to <a href="https://mdcode2021.medium.com/api-call-in-swift-part-1-urlsession-c013fd9e575f">part 1</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OvJYsayoHdyUKe23" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Service Manager</h3><ul><li>This time we are creating a service manager separated from our view model.</li><li>This class will contain things related to network calls only.</li><li>We are creating function as static so that, we can access that without creating its object.</li><li>You can see there is a completion of the result, counting data and error. We will handle it while calling this function.</li><li>Also, we have created an enum case to handle the errors.</li><li>Lastly — In my code, you will see spaces before the colon, that&#39;s not a good habit, I am trying to change it for the last 2 months. 😇</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7fc10482d1f9a8fc2d4039adf5a3977/href">https://medium.com/media/d7fc10482d1f9a8fc2d4039adf5a3977/href</a></iframe><h3>Weather View Model</h3><ul><li>Our view model is making that network call in its initialization.</li><li>We are handling the errors and updating the alert title based on success and failure.</li><li>We made it observable so that we can observe the properties in UI.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0aaa2f0ceb6a45ceb976c3d365a366e/href">https://medium.com/media/b0aaa2f0ceb6a45ceb976c3d365a366e/href</a></iframe><h3>Thats it for PART 2</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FhR6Q01jCXOr31wctJw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FhR6Q01jCXOr31wctJw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FhR6Q01jCXOr31wctJw%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c029745ddb3606971ed849b1834d1e68/href">https://medium.com/media/c029745ddb3606971ed849b1834d1e68/href</a></iframe><h3>Thanks for Reading 💯</h3><p>Me on: <a href="https://www.linkedin.com/in/my-pro-file/">LinkedIn</a> — <a href="https://github.com/myawesomehub">GitHub</a></p><p>Check this link: <a href="https://bit.ly/38HOQeb">https://bit.ly/38HOQeb</a></p><p>Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter <a href="http://tinyletter.com/TheLeanProgrammer">tinyletter.com/TheLeanProgrammer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88075bf0210d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theleanprogrammer/api-call-in-swift-part-2-completion-error-handling-88075bf0210d">API Call in Swift Part 2</a> was originally published in <a href="https://medium.com/theleanprogrammer">TheLeanProgrammer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>