In this tutorial we’re going to build a horizontal scroll view (also known as horizontal list) that is placed along the top of the screen. It’s a simplified version of Instagram stories feature which enables you to horizontally scroll through the images of people you follow. Instead of images, we’re going to use circles to …
Month: May 2020
How to return multiple values from a function in Swift
Tuples can be used to return multiple values from Swift functions. A tuple allows you to group together multiple values of different types which can then be returned from a function as a single entity. Here is an example of a function which returns a String, an Int and a Double: func returnMultipleValues() -> (String, …
How to iterate over enum cases in Swift
You can iterate over all of the possible cases of an enumeration in Swift by making it conform to the CaseIterable protocol. When using CaseIterable, you can access a collection of all enum cases by using a allCases property and then iterate over it as an array. The order of allCases collection depends on the declaration order …
SwiftUI DatePicker tutorial – how to create and use DatePicker in SwiftUI
DatePicker is a control in SwiftUI which enables you to input (by selection) date and time values. In order to properly use a DatePicker, you need to back it with a State variable storing the selected date. This tutorial shows you how to create and use a DatePicker in SwiftUI. In its simplest form, a DatePicker can be …
How to check if an object is of given type in Swift
In order to check if an object is of given type in Swift, you can use the type check operator is. Given an example class Item, you can check if the object is of its type like that: let item = Item() if item is Item { print(“object is of Item subclass type”) } else { print(“object is …
How to iterate over lines in a string in Swift
You can iterate (loop) over lines in a string using enumerateLines(invoking:) method which calls a given closure on each line of the string: var str = “Foundation\nSwift\nString” str.enumerateLines { (line, _) in print(line) } The above code prints out each line separately. Get an array containing all of the lines in a string In order to split …
How to iterate over characters in a string in Swift
You can iterate (loop) over a string’s characters using a regular for loop by treating it as an array: let str = “Foundation Swift String” for char in str { print(“character = \(char)”) } The above code prints out each character in a new line. Alternatively, you can use the forEach(_:) method on a string, which calls …
How to split a string into an array of strings in Swift
In order to split a given string into an array containing substrings from the original string, the components(separatedBy:) method can be used. Given a string of items separated by spaces, here is how to get an array of components separated by space: let str = “Foundation UIKit SwiftUI String Components” let items = str.components(separatedBy: ” …