iOS9 Swift File Creating NSFileManager.createDirectoryAtPath with NSURL

I figured this one out. createDirectoryAtPath() is unable to process a path with the “file://” prefix. To get a path without the prefix you must use path() or relativePath(). let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) let logsPath = documentsPath.URLByAppendingPathComponent(“logs”) do { try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.path!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { … Read more

Get random elements from array in Swift

Xcode 11 • Swift 5.1 extension Collection { func choose(_ n: Int) -> ArraySlice<Element> { shuffled().prefix(n) } } Playground testing var alphabet = [“A”,”B”,”C”,”D”,”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,”Q”,”R”,”S”,”T”,”U”,”V”,”W”,”X”,”Y”,”Z”] let shuffledAlphabet = alphabet.shuffled() // “O”, “X”, “L”, “D”, “N”, “K”, “R”, “E”, “S”, “Z”, “I”, “T”, “H”, “C”, “U”, “B”, “W”, “M”, “Q”, “Y”, “V”, “A”, “G”, “P”, “F”, “J”] … Read more

How do I insert an element at the correct position into a sorted array in Swift?

Here is a possible implementation in Swift using binary search (from with slight modifications): extension Array { func insertionIndexOf(_ elem: Element, isOrderedBefore: (Element, Element) -> Bool) -> Int { var lo = 0 var hi = self.count – 1 while lo <= hi { let mid = (lo + hi)/2 if isOrderedBefore(self[mid], elem) { … Read more

CLLocation Manager in Swift to get Location of User

You are missing two things. First, you have to ask for permission using requestAlwaysAuthorization or requestWhenInUseAuthorization(). So your viewDidLoad() should be like this: var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } Second, … Read more