If you need to read a very large file you’ll want to stream it so you’re not loading the entire thing into memory at once. Here’s a snippet for doing that.
Tag: swift
Read a File From Xcode Playgrounds
If you need to have some data in an external file and read it in playgrounds, here’s how to do it in Xcode 11.3 using Swift 5.1.
How to Reverse a Number Mathematically
Here’s a simple method for getting the reverse of a positive integer.
Create a Circular Array with the Modulo Operator
If you need to continue looping over an array after you’ve reached the end, you can use the modulo operator to start the index back at 0.
How to Consume an External API in iOS
This is a very gentle introduction to fetching data from an external API in iOS. This tutorial is aimed at beginners and doesn’t assume any prior knowledge.
Fibonacci Sequence Explained
If you’re not familiar with the Fibonacci sequence, the gist is that each number is the sum of the two numbers before it, starting from 0 and 1.
How to Perform a Binary Search in Swift
The basic idea behind a binary search is that you take the midpoint of a sorted array and compare that with the item you’re searching for. The key thing to remember is that the array must be sorted. The steps are:
Trim Whitespace From UITextField in Swift
Let’s say you have a text field and you want to disable the Save button until the user enters something. But you don’t want to allow whitespaces. Here’s one way to handle that. 1. Hook up an outlet to your bar button item so you can set its isEnabled state later. 2. Hook up an… Continue reading Trim Whitespace From UITextField in Swift
Rounded Corner Button in Swift
It’s very simple to create buttons with rounded corners. Create a button like you normally would in Interface Builder, create an Outlet to it, and then in viewDidLoad, set the attributes like this: button.layer.borderWidth = 3.0 button.layer.borderColor = UIColor.white.cgColor // Set this to the background color of your button button.layer.cornerRadius = 8.0
Play Music in iOS
Here’s a utility to play background music for iOS in Swift: First, import AVFoundation. Then add: var backgroundMusicPlayer: AVAudioPlayer! func playBackgroundMusic(filename: String) { let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil) guard let url = resourceUrl else { print(“Could not find file: \(filename)”) return } do { try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url) backgroundMusicPlayer.numberOfLoops = -1 //… Continue reading Play Music in iOS