Swift Code Snippets
Below are some useful Swift code snippets for use in everyday projects.
When dealing with directories and files it may be necessary to check for their existence. In Swift, checking for the existence of a directory and file is done in the same manner. Below is an example of how to do this.
// Example directory and file. var exampleDirectory = "/Users/demouser/demo" var exampleFile = "/Users/demouser/demo/demo.txt" // File manager object. var fileManager = FileManager.default // Check if the directory exists. if fileManager.fileExists(atPath: exampleDirectory) { print("The directory '\(exampleDirectory)' exists.") } else { print("The directory '\(exampleDirectory)' doesn't exist.") } // Check if the file exists. if fileManager.fileExists(atPath: exampleFile) { print("The file '\(exampleFile)' exists.") } else { print("The file '\(exampleFile)' doesn't exist.") }
Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.
// Minimum and maximum values for random number. var minVal = 1 var maxVal = 59 // Generate random number. var randomNumber = Int.random(in: minVal...maxVal) // Display the number the number. print(randomNumber)