Pull to refresh
24.52

Swift *

General-purpose, multi-paradigm, compiled programming language

Show first
Rating limit
Level of difficulty

LeetCode, Hard++ (Acceptance 24%, Latest): 2867. Count Valid Paths in a Tree. DFS. O(n). Swift

Level of difficulty Hard
Reading time 2 min
Views 1.5K

The intuition is to employ a depth-first search (DFS) approach through the tree.

During each step in the traversal, we perform the following key calculations:

1. Determine the path that ends at the current node.

2. Compute two different subtree paths that traverse the current node.

3. Maintain an array that keeps track of the cases where paths contain either 0 or 1 prime number.

This method allows us to efficiently count the valid paths in the tree while considering the presence of prime numbers.

Read more
Total votes 9: ↑4 and ↓5 -1
Comments 1

LeetCode, Hard: 2818. Apply Operations to Maximize Score. Swift

Level of difficulty Hard
Reading time 4 min
Views 1.1K

Time complexityO(max(nums) * log(max(nums)) + n * log(n)). Accounting for computing prime scores, using the stack to compute next greater elements, and sorting the tuples.

Space complexityO(max(nums) + n). Considering the space required for arrays and the stack used for computation.

Read more
Total votes 2: ↑1 and ↓1 0
Comments 1

LeetCode, Hard, last two problems: 2809. Min Time to Make Array Sum At Most x & 2813. Max Elegance of a K-Length Subseq

Level of difficulty Hard
Reading time 3 min
Views 761

2809. Min Time to Make Array Sum: Efficient Swift solution, using dynamic programming, for minimizing time to reach a sum in arrays A and B. Time: O(n²), Space: O(n).

2813. Max Elegance of K-Length Subseq: Swift code for elegantly selecting unique k-length subsequences with profit and categories. Solution uses sorting and iteration. Time: O(nlogn), Space: O(n).

Github: https://github.com/sergeyleschev/leetcode-swift

Read more
Total votes 1: ↑1 and ↓0 +1
Comments 2

LeetCode 2532 (Hard++, Extra Category, Amazon). Time to Cross a Bridge. Swift solution

Level of difficulty Hard
Reading time 5 min
Views 1K

Hard++, Extra Category.

Amazon.

Overflow checks have been taken into consideration. The maximum time to move a box is at most 4 * 1000 (four steps to move the box, each taking 1000 time). With at most 1e4 boxes, the total time is at most 4e7, ensuring the solution is safe.

Read more
Rating 0
Comments 0

iOS Dev Skills. Performance Review

Reading time 2 min
Views 840

CTO: Balancing Leadership and Architecture.

As a CTO, effective leadership goes beyond technical architecture. Conducting regular performance reviews is a crucial part of managing teams.

Note: The performance review schedule may vary depending on the specific
company's policies and guidelines.

For early-stage startups, lacking CTO expertise in conducting performance reviews is common. In my experience, I've tailored grades to encompass all aspects of professional iOS development, keeping project-specific needs in mind. Being the first in the team can offer significant growth opportunities. However, acknowledging any lack of people management skills and compensating through continuous growth is essential.

I've compiled my insights on structuring the iOS development department, conducting performance reviews, and most importantly, emphasizing the significant distinctions between developers' levels based on well-defined criteria.

Read more
Rating 0
Comments 0

LeetCode 2801 (Hard, Acceptance 14.5%). Count Stepping Numbers in Range. DP. Handles large inputs (10^9 + 7)

Level of difficulty Medium
Reading time 3 min
Views 652

Given two positive integers low and high represented as strings, find the count of stepping numbers in the inclusive range [low, high].

A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.

Return an integer denoting the count of stepping numbers in the inclusive range [low, high].

Since the answer may be very large, return it modulo 10^9 + 7.

Hard, Acceptance Level 14.5%.
Dynamic Programming (DP).
Efficiently handles large inputs (10^9 + 7).

Latest and Most Hardest Problem.

Read more
Rating 0
Comments 0

LeetCode 2790 (Hard). Maximum Number of Groups With Increasing Length. Solution of the day. O(N logN). Math

Level of difficulty Medium
Reading time 3 min
Views 1.2K

Simple Swift Math Solution.

Time complexity: O(N logN).

The time complexity of this solution is dominated by the sorting step, making it O(N logN), where N is the length of the input array usageLimits. The rest of the operations involve simple arithmetic and comparisons, which take linear time. Therefore, the overall time complexity of the function is O(NlogN).

Only 10 lines of code.

Read more
Rating 0
Comments 0

How to Make an E-commerce App in SwiftUI

Level of difficulty Medium
Reading time 4 min
Views 917

In this guide, I'm going to walk you through how to create a simple e-commerce app using SwiftUI and Firebase. The app will include basic functionalities such as product listing, shopping cart, and user authentication.

Before we get started, you should have the following installed:

Read more
Rating 0
Comments 1

LeetCode 2612 (Hard). Minimum Reverse Operations. Swift. BFS. O(n+k). O(n)

Level of difficulty Hard
Reading time 3 min
Views 1.5K

LeetCode 2612 (Hard). Minimum Reverse Operations.

The algorithm follows a breadth-first search (BFS) approach to determine the minimum number of reverse operations needed to bring the 1 to each position in the array.

To speed up the algorithm, we mark banned positions with -2 instead of using set lookups. This optimization reduces the constant coefficient and improves the speed of the algorithm, but it may still result in a time limit exceeded (TLE) error.

For each visited position, there are potentially O(k) target positions that can be reached through reverse operations. To avoid the multiplicative cost of iterating over all these potential positions, we update the nextNode2s array. This array initially points forward by 2, but we update it dynamically to point beyond all the target positions considered for each visited position. This optimization helps improve the efficiency of the algorithm and avoids unnecessary computations.

Read more
Total votes 2: ↑2 and ↓0 +2
Comments 0

LeetCode 956 (Hard). Solution of the day. Tallest Billboard. Swift. DP

Level of difficulty Hard
Reading time 2 min
Views 2.3K

Solution of the day.
LeetCode 956 (Hard). Tallest Billboard.

The code uses dynamic programming to solve the problem. It maintains a dictionary dp, where the keys represent the possible height differences between the two billboards, and the values represent the maximum sum of heights achieved for each height difference.

Read more
Total votes 4: ↑3 and ↓1 +2
Comments 0

Array of weak in Swift

Level of difficulty Medium
Reading time 2 min
Views 4K

In Swift, when working with objects, it’s important to manage memory correctly. One way to do this is by using weak references to avoid retaining objects too long and causing memory leaks. In this article, we will discuss how to create an array of weak references in Swift using a generic wrapper.

Read more
Total votes 1: ↑1 and ↓0 +1
Comments 0

SwiftUI & ChatGPT. The world is changing. Again

Level of difficulty Easy
Reading time 4 min
Views 2.9K

Everything that follows from this point forward input prompts, followed by ChatCGP’s responses, complete with sample code in Swift.

> Hey ChatGPT, can you make a SwiftUI registration form with name, address and city fields?

Read more
Total votes 5: ↑4 and ↓1 +3
Comments 1

Swift 5.7: Regex. Shorthands for optional unwrapping. Unlock existentials for all protocols

Level of difficulty Medium
Reading time 3 min
Views 989

Swift 5.7: Regex. Shorthands for optional unwrapping. Unlock existentials for all protocols.

Shorthands for optional unwrapping. Improved type inference for complex closures. Better string parsing with Swift Regex. Creating a Regex with Regex literal. Creating a Regex using RegexBuilder. Unlock existentials for all protocols.

Read more
Rating 0
Comments 0

Building your own CLI with Swift Programming Language

Level of difficulty Easy
Reading time 5 min
Views 3.2K

Command-line interfaces (CLI) are a common way to use applications. In iOS, we usually use scripting languages like Bash or Ruby to build those CLIs and automate mundane tasks. The most popular CLI for app signing and build automation is, without a doubt, Fastlane, which was initially written in Ruby. Fastlane is a great tool, convenient and fairly easy to use, and a lot of effort came into building it.

However, there's a great chance you considered moving away from Fastlane to avoid learning Ruby and to lower the entry threshold for your developers. Setting up a Ruby environment could be quite tedious and require additional devs' expertise to write and support those scripts.

Explore how to build your own command line tools with Swift in this article.

Read more
Total votes 2: ↑2 and ↓0 +2
Comments 5

The first joint project with friends or how it turned out that each of us is good in his field

Level of difficulty Easy
Reading time 3 min
Views 634

Not so long ago, a good friend of mine suggested that I could make a mobile application that could allow him, as well as other less experienced football scouts, to be able to collect and store analytical information on football players, to provide reports to clubs or agencies and also to communicate with more advanced scouts.

How can it be useful?

At the moment, there is no analogue to similar applications in the Russian segment. This is because there is no great need for it. Clubs don't want to spend money on it, and agencies don't have such resources. Moreover, the implementation takes too much time. And scouts are used to working according to their own schemes and storing information in notebooks and so on. However, it does not mean that such an application cannot be useful for young scouts. It would teach you how to make reports correctly, focus on the data that football clubs and agencies are interested in, and would also allow you to select those scouts who would have potential.

By that time, I had already worked enough in mobile development to make such an application. However, the right approach for the implementation was required, in order to understand what this product should represent as a result, and also design.

By a lucky coincidence, the last question disappeared by itself because my friend's girlfriend was just finishing her design studies at Yekaterinburg University, so her graduation project became our design.

Read more
Total votes 1: ↑1 and ↓0 +1
Comments 0

Creating UITableView with a dynamic header

Reading time 6 min
Views 4K

Hello there! Recently, I had very cool experience at my work. I needed to set tableView with a dynamic header. The information in the header was complete in the initial state, and when the user was scrolling the table, some part in the header was smoothly hiding and the main part remained on the top. Cool, right?

Read more
Total votes 2: ↑2 and ↓0 +2
Comments 4

Composable Contexts Architecture

Reading time 5 min
Views 2.2K

Let’s talk about app architecture and the approach I apply as an iOS software engineer in a few companies. My team and I were trying to build something solid without slipping into a dense swamp where following the rules distracts you from actual business domain code. As a result, we got something that works for us and good enough to be told from my point of view.

Read more
Rating 0
Comments 0

SwiftUI and MVI

Reading time 5 min
Views 7.5K

UIKit first appeared in iOS 2, and it is still here. Eventually we got to know it well and learned how to work with it. We have found many architectural approaches. MVVM, the most popular architecture in my opinion, has strengthened its position with the release of SwiftUI, while other architectures seemed to have some kind of problematic relationships with SwiftUI.

But what if I told you that Clean Swift, VIPER and other approaches can be adapted to SwiftUI. What if I told you that there are some modern architectures which might be as good as MVVM or even better.

We will talk about MVI.

Read more
Rating 0
Comments 0

Confusing extensions in Swift

Reading time 4 min
Views 2.1K
This post is a little bit the information aggregator. If you find a mistake, you could write to me about it I really appreciate that. Have a nice read.

Example with JSONDecoder


What would happen if we run the following piece of code?

struct Test<T>: Codable where T: Codable {
    enum CodingKeys: String, CodingKey {
        case value
    }
    
    let value: T
    let info: String
}

extension Test {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.value = try container.decode(T.self, forKey: .value)
        self.info = "Default init(from decoder:)"
    }
}

extension Test where T == String {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.value = try container.decode(T.self, forKey: .value)
        self.info = "Custom init(from decoder:)"
    }
}

let data = #"{"value":"Hello, World!"}"#.data(using: .utf8)!
let object = try? JSONDecoder().decode(Test<String>.self, from: data)
print(object.debugDescription)

Try thinking for 5 seconds about the result.

The result
Optional(
    Test<String>(
        value: "Hello, World!", 
        info: "Default init(from decoder:)"
    )
)


Read more →
Rating 0
Comments 0
1

Authors' contribution