Skip to main content

Posts

Showing posts from 2015

Solution to Mac App Store not loading (El Capitan 10.11.2)

If you find that the Mac App Store opens but that it endlessly tries to load its content but just keeps spinning and spinning the loading wheel, then there is a solution . It was posted to the Apple forums and is in two parts. First remove the following files (if they exist): ~/Library/Preferences/com.apple.appstore.plist ~/Library/Preferences/com.apple.storeagent.plist which you can do in one of two ways: either use the terminal, as advised in the original solution, or open Finder,  select the Go menu hold down the option key (alt) select Library from the menu double-click Preferences folder to open it and remove: com.apple.appstore.plist and com.apple.storeagent.plist Next, restart your Mac while resetting the NVRAM using the following steps: Shut down your Mac. Locate the following keys on the keyboard: Command (⌘), Option, P, and R. Turn on your Mac. Press and hold the Command-Option-P-R keys immediately after you hear the startup sound. Hold these keys until t

Hacking my life: A year of immersion in foreign languages

If it's possible to learn a programming language with the resources of the Internet, is it also possible to learn a foreign language? My New Year's resolution (2016) is to finally try and expand my vocabulary and ability in real-world languages by using the tools available to me on the Internet and without adding any time specifically dedicated to language learning. Yes, I've tried Duolingo and it's brilliant but I want something less abstract from life and which is inbuilt with even less friction, something that slots in place of what I already do. So I've started hacking my life to make learning more everyday. Step 1: I've deleted all UK news apps from my phone and downloaded foreign ones instead. I've installed Le Monde, Spiegel Online, SZ.de, Republic.it, ARA.CAT, and changed Huff Post to the French edition in the app's settings. I've also downloaded the France 24 news broadcast app. The first thing to note is that typically news apps for t

iPad Pro: Resurrecting the single-device multiplayer game

Back in the mists of time when the first iPad was released there quickly followed a range of games with multiplayer modes for 2-4 players. Some used the sides of the screen, some the corners, and others split the screen in two. The size of the iPad Pro, which is closer to the size of a gaming board than any other iPad thus far, started me thinking about whether all those old games would still run in iOS 9.1 on the Pro, and what they'd be like. It turns out that the games I remember playing back on the iPad 1 (with a single exception) still run and are well suited to the larger iPad with far less finger clashing (and lag) than before. Multiponk by Fingerlab (£2.29/$2.99) This first game took me a while to track down because I couldn't remember the title but sifting through the bottom of my purchased list (for the oldest apps I own) I located Multiponk, a 1-4 player game deflecting ball bearings to stop them getting past your bat. It's a must play for those seeking a

Bytes for Beginners: Representation of negative numbers in binary using Swift (two's complement)

When I initially wrote the bytes for beginners series of posts I never got around to discussing the representation of negative numbers in binary or how we might use Swift to understand this. So let's begin now with bit casting, which is the act of transforming a bit of one type into something of another type. Here's an example, we have a UInt8 (an unsigned 8-bit integer), which can store any number from 0 to 255 and we want to cast it to an Int8 (a signed 8-bit integer), which holds a number from -128 to 127. unsafeBitCast(UInt8(128), Int8.self) // -128 unsafeBitCast(UInt8(255), Int8.self) // -1 What is happening here is easiest explained by Dr. Math : The numbers 0 to 127 are positive; numbers 128 to 255 represent -128 to -1. So if we think of this in binary terms String(128, radix:2) // 10000000 String(255, radix:2) // 11111111 then 10000000 in what is known as a  two's complement representation (or Int8's language) is -128, where in the language of UInt

Random numbers in Swift: wherefore art thou arc4random_uniform (Xcode 7.1.1, iOS; update with info on SecRandomCopyBytes; update Xcode 8 beta 6, Swift 3)

** Jump to Swift 3 code ** Two years ago the case was closed, NSHipster in his wisdom told us to use arc4random_uniform for random numbers but then Apple go and remove it from the Darwin.C.stdlib header file in Xcode 7. While it still works, this makes it feel kind of dirty to use it. Has it been removed for a reason? Or is it simply waiting to be put back once bugs are ironed out? The issue has been identified on Apple's forums but no definitive response appears. (Thanks to  @mofodox for drawing my attention to its absence and prompting this investigation.) This prompted me to look around at the other available random functions in the stdlib, and here's some code that I started throwing together. srand(1) // seed the starting point rand()%100 // restrict the upper value lrand48() mrand48() random()%100 random()%100 + 1 // set upper and lower values var ccc = UInt16(10) seed48(&ccc) // seeding a 48 function lrand48() mrand48() For an explanation I turned to IBM

Creative Cloud Workarounds: Failure to recognise installed apps or reinstall from Creative Cloud app

I've been using Creative Cloud since it was first released and it's not always (well, in truth, never really) been a perfect relationship. In the early days there were the syncing bugs that made it impossible to utilise the free cloud storage (which at one point was whisked away for a few months, if I remember correctly), then there was the bug that forced me to reformat an iMac because the Adobe Crash Daemon was eating all the hard-drive space. Now I have a MacBook where the Creative Cloud app refuses to acknowledge the existence of the installed Adobe apps, and any attempt to remove and reinstall results in the install stalling around 42%. This has left me with two options, a fresh formatting of yet another hard-drive or AirDropping apps from a desktop iMac to the MacBook. I've chosen to AirDrop for now, which has until my latest attempt worked perfectly with simply dragging the AirDropped app folders into Applications. There was just one glitch this time (which was ca

Old Tech: Lessons learnt from the Garmin FR50

In the beginning I bought the Garmin FR50 from eBay for a price of around £20, not realising that it was a watch that had replaceable rather than rechargeable batteries. After the discovery I read many horror stories of the short life of the batteries and feared the worst. The reality turns out much better. This watch was my first step into the world of fitness wearables. I wanted a device that could simply tell me the pace at which I was running so I didn't have to keep listening out for audio notifications from MapMyRun. After fitting new batteries in the watch (and the accompanying footpod) and calibrating to align with the distance and speed information on my phone everything has been working a treat. And those batteries have been ticking away nicely for the past four months or so without needing to be replaced. Regular use I run on average two to three times a week and cover 20-30 km. The device also acts as my everyday watch and a constant reminder that I run. Bu

Review: Swift Algorithms & Data Structures (Wayne Bishop)

The arrival of Swift has been a marvellous education, it has been a reason for so many writers and bloggers to revisit core elements of programming and to explain them within the context of this new language. Wayne Bishop 's book continues this tradition by taking up the challenge of presenting us with well-established data structures explained through Swift. Each data structure that Swift Algorithms & Data Structures: A practical guide to concepts, theory and code presents is accompanied by a diagrammatic illustration, alongside a clear and concise explanation, followed by code implementations of how the data structures can be utilised in Swift. I can't imagine a more straightforward presentation of the data structures contained in the book, and if you wish to be a more intelligent programmer then this book deserves your time. How quickly you progress through the book will depend on your current level of programming knowledge. The book begins with the List str

From binary to decimal values in Swift (updated Swift 3, Xcode 8)

Before we start it definitely needs to be noted that Swift has binary literals: 0b11011111 // 223 And also that you can convert a binary String to a decimal using the C standard library : strtoul("11011111", nil, 2) // 223 Bool array as a binary representation But why should this stop the fun. So first let's begin with a Bool Array, which I've typealiased to Bit for clarity. I begin with Bool because it prevents anything but 0 and 1 (or rather true and false) being used. typealias Bit = Bool let B1 = true let B0 = false func binaryToDecimal(binary:[Bit]) -> Int { var bitValue = 1, total = 0 for b in binary.reverse() { if b == true { total += bitValue } bitValue *= 2 } return total } binaryToDecimal([B1,B1,B0,B1,B1,B1,B1,B1]) // 223 Swift 3, Xcode 8 typealias Bit = Bool let B1 = true let B0 = false func binaryToDecimal(binary:[Bit]) -> Int { var bitValue = 1, total = 0 for b in binary.rever

Protect yourself: Retrieving penultimate values from arrays in Swift

The crashers One of the first thoughts that comes to the mind when retrieving penultimate values is to count the array and work backwards. let values = ["2","4","6"] values[values.count - 2] // crashes if count is less than 2 values[values.endIndex.predecessor().predecessor()] // an alternative way to do the same thing, also crashes if count is less than 2 If the array contains only one element, however, the app will crash. Similarly if we reversed the array and worked forwards, an array of 1 item or less would again crash the attempt to retrieve a penultimate value. let values = ["2","4","6"] values.reverse()[1] // crashes if count is less than 2 The reason for the crash is that, as with any array, an attempt to retrieve a value beyond its bounds the result is exactly this: a crash. Protected but error prone One form of protection against crashes is to use advance and to ensure we don't advance beyond the bound

Swift 2.0: More crashing and throwing in Aldwych (a JSON Parser)

A conversation started on twitter yesterday surrounding the inability of subscripts to throw errors. It was begun by  @krzyzanowskim  and gave me the opportunity to think even further about the approach to error handling I am employing in Aldwych 2.0 (a JSON parser for Swift). Standard approach My standard approach is to follow the Swift standard library way of doing things as much as possible. The core example being to throw errors when something user-led might not be possible: e.g. a file chosen is of the wrong type or the data in the file is corrupted, or the data simply doesn't parse. This logic means that  NSJSONSerialization  has throwing methods as standard for creating objects from JSON and for creating JSON from objects. While NSData goes halfway and has a choice of failable initializers and throwing intializers in iOS 9 (Xcode 7 beta 4). For example: init(contentsOfURL url: NSURL, options readOptionsMask: NSDataReadingOptions) throws and init?(contentsOfURL ur

Swift 2.0: throwing vs failing vs crashing vs bool

Updating Aldwych  (a JSON parser for Swift), I wrote a method for changing a value in a dictionary that closely echoes the standard library but which has one important parameter added: typesafe. public mutating func updateValue(value:AnyObject, forKey key:String, typesafe:Bool = true) So what happens is that if typesafe is set to false any type can be exchanged for any (JSON compatible type) but if typesafe is set to its default (true) and we try to set a different type from the current one then the value won't be updated (unless it was null). A similar thing happened in Aldwych 1.0, but that was before Swift gained error do-try-catch functionality. There an attempt to change types in typesafe mode resulted in silent failure. The update didn't happen but there was no way of knowing this without checking. When throwing and catching doesn't fit With the new ability to throw and catch errors it seemed at first an ideal solution for Aldwych's type safety that an err

Updating Aldwych (Part 1): Parsing JSON with recursive enums in Swift

The purpose of Aldwych from the very beginning has been to provide JSON parsing that is type safe, flexible and familiar. And when recursive enums were first announced by Chris Lattner at WWDC 2015, I hoped they would enable a great internal simplification of the JSON parser. Step One With this hope in mind, and with a handkerchief filled with sandwiches tied to a stick, I decided to experiment with recursive enums by making the core type in Aldwych simply this: public enum JSONValue { case JString(String), Number(NSNumber), JBool(Bool), Null indirect case JArray([JSONValue]), JDictionary([String:JSONValue]) } which was a pretty good start but I encountered one very particular problem: the for-in loop. If you think about an Array we loop through it using for v in array {} but in a Dictionary we use for (k,v) in dictionary {} . This means that the Element type of an Array is a single value while that of a Dictionary is a tuple. This was the first hurdle becau

Swift: What do I understand about flatMap? (updated 27 July 2015)

Sometimes you read a blogpost and it is only by responding to the blogpost that you come to an understanding of your own understanding. I've written a lot about fumbling with flatMap , but it wasn't until I read Natasha the Robot's recent post (and saw it evolve in response to comments) that I brought all those things together into a list of what I currently understand about flatMap. And once I'd noted down what I knew about flatMap , I suddenly became scared that I might forget what I currently know about flatMap, so I'm reproducing the comment I made here. Comment So far I've come to the following understandings: 1. it [i.e. flatMap] can be used to reduce an array of optionals to non-optionals, e.g. [String?] to [String] , as you've done here [in the post] 2. it can reduce nested arrays into a single array, e.g. [[1,2,3],[4,5,6]] to [1,2,3,4,5,6] 3. it works at a level one deeper than map (as seen in point 2), which means that if you pass it a

Deferring and Delegating in Swift 2 (Xcode 7 beta 3) - updated

We're used to the Cocoa framework having classes that are assigned delegates from actions such as XML parsing. But what if we want to create our own types with our own delegates. protocol Main { var delegate:Delegate {get set} } protocol Delegate { func started() func finished() } The above code defines a simple delegate relationship using protocols. There then follows two types that fulfil these protocols: struct MyMain: Main { var delegate:Delegate func doSomething() { delegate.started() print(1+1) delegate.finished() } } struct MyDelegate: Delegate { func started() { print("it's started") } func finished() { print("it's finished") } } As long as the main type is assigned a delegate it fulfils the protocol but the delegate itself must have started() and finished() methods because they are outlined in the delegate protocol. The doSomething() method in the main type co