<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Patrick O&#39;Leary on Medium]]></title>
        <description><![CDATA[Stories by Patrick O&#39;Leary on Medium]]></description>
        <link>https://medium.com/@oleary.audio?source=rss-7d9a4d5eb30e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EG9oM1MV-kOlOgef2w43IQ.jpeg</url>
            <title>Stories by Patrick O&amp;#39;Leary on Medium</title>
            <link>https://medium.com/@oleary.audio?source=rss-7d9a4d5eb30e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:00:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleary.audio/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I NSAttribute my success to a good night’s sleep and a beer heavy diet]]></title>
            <link>https://medium.com/@oleary.audio/i-nsattribute-my-success-to-a-good-nights-sleep-and-a-beer-heavy-diet-5a31ba36b0f?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a31ba36b0f</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Mon, 21 May 2018 16:00:41 GMT</pubDate>
            <atom:updated>2018-05-21T20:03:41.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>A small Swift extension library for NSAttributedString</h4><p>Hello there! It’s been a while! This is definitely my first post in about six months, so I apologize if you’ve been sitting at home, waiting breathlessly for me to finally publish some life-changing Swift code. Maybe in a future post I’ll talk about what I’ve been up to. But not today! Today we’re going to talk about <a href="https://developer.apple.com/documentation/foundation/nsattributedstring">NSAttributedStrings</a>.</p><h4>Before we begin, a quick side note</h4><p>My new goal for this blog is to be less of a “here’s how you do this in Swift” kind of a thing, and more of a “here’s how I’m doing this in Swift, what are <em>your </em>thoughts?” I’ll describe a problem that I had to solve, how I went about it, what my final solution looked like, and maybe what some other solutions could look like. There are plenty of tutorials out there that tell you ‘how to do something.’ I want to approach this from a practical point of view. And seriously, in all likelihood the solutions I come up with are probably far from the best ones out there. Have a better idea? Leave a comment!</p><h4>Okay Pat, enough of your personal feelings</h4><p>Anyway. Most of the time, when we set a string to a label, it looks something like this:</p><pre>someLabel.font = UIColor.red<br>someLabel.font = UIFont(name: &quot;cool_font_bro&quot;, size: 20)<br>someLabel.text = &quot;Hey I&#39;m a label!&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*ABig8fgqnExKx64dHTFktg.png" /></figure><p>Easy! But what if we want different parts of that text to be written in different colors? Or different fonts? What would we do then? You might try and make an individual label for each part of the text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*a7fHdJVREk_qKOH-wSU41g.png" /><figcaption>WHY PAT!? WHY WOULD YOU EVER DO SOMETHING THIS WAY!?</figcaption></figure><p>I made those labels overlap on purpose, but it was probably obvious to you why this was a bad idea. (It was soooo obvious to me. I definitely never tried it this way myself the first time I had to do this…) It’s gonna get super tedious to set the frames or layout constraints that you’d need to make that work. And then if the text in those labels changes at all, you’re gonna have to programmatically adjust those constraints.</p><p>What we need to use are NSAttributedString and NSMutableAttributedString. NSAttributedStrings are objects that manage character strings as well as a set of properties. (NSAttributedString is read only, while NSMutableAttributedString can be… wait for it… mutated). These properties can be applied to a range of the characters that are held by the object. For example:</p><pre>let hotDog = NSMutableAttributedString(string: &quot;Hot Dog!&quot;)<br>let redAttributes = [<br>     NSAttributedStringKey.foregroundColor : UIColor.red<br>]<br>let blueAttributes = [<br>     NSAttributedStringKey.foregroundColor : UIColor.blue<br>]<br>let redRange = NSRange(location: 0, length: 3)<br>let blueRange = NSRange(location: 4, length: 4)<br>hotDog.addAttributes(redAttributes, range: redRange)<br>hotDog.addAttributes(blueAttributes, range: blueRange)<br>someLabel.attributedText = hotDog</pre><p>Will give us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*g_NvaFTpt-oyJaID42jwAg.png" /></figure><p>Note that we used an NSRange to calculate the range of characters that we apply the attributes to. We define the attributes as a dictionary with an NSAttributedStringKey and a corresponding value.</p><p>Now that’s all well and good, and there’s a good chance you already knew most of what I just told you. And if you have dealt with attributed strings in the past, you know what a pain they can be and how ugly your code can end up looking.</p><p>Think about it: every time you want to add an attribute you have to figure out the range you want to apply it to. And if anything about the text or attributes needs to change, you have to figure it out again. Take a look at this monstrosity:</p><pre>let text = &quot;I&#39;ve got a bad feeling about this&quot;</pre><pre>let attributedText = NSMutableAttributedString(string: text)</pre><pre>text.enumerateSubstrings(in: text.startIndex..&lt;text.endIndex, options: .byWords) { (substring, substringRange, _, _) in<br>     if substring == &quot;bad&quot; {<br>          let range = NSRange(substringRange, in: text)<br>           attributedText.addAttributes([<br>               NSAttributedStringKey.foregroundColor : UIColor.red<br>          ], <br>               range: range)</pre><pre>     } else if substring == &quot;this&quot; {<br>          let range = NSRange(substringRange, in: text)<br>          attributedText.addAttributes([<br>               NSAttributedStringKey.foregroundColor : UIColor.blue<br>          ], <br>              range: range)<br>     }</pre><pre>}</pre><pre>someLabel.attributedText = attributedText</pre><p>That’s a lot of ugly looking code just to get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*T0jhgWJkMfRhCDcqRKHe-g.png" /></figure><p>Imagine if we had to add some kind of dynamic behavior to this label. Our code could very quickly becomes a huge mess of calculating NSRanges and adding attributes. There must be a better way!</p><h4>A functional NSAttributedString library</h4><p>First, I want to refactor how we convert strings to NSAttributedString. There’s nothing wrong with <strong>NSMutableAttributedString(string: “Hot Dog!”)</strong>, but it’d be pretty easy to make this more readable and declarative:</p><pre>extension String {<br>      func asNSAttributedString() -&gt; NSAttributedString {<br>          return NSAttributedString(string: self)<br>     }<br>}</pre><pre>someLabel.attributedText = &quot;Everybody dance&quot;.asNSAttributedString()</pre><p>It’s a small thing, but to somebody else reading your code, I think this is a bit easier to read. Also important: the reason I use <strong>NSAttributedString</strong> here — rather than <strong>NSMutableAttributedString</strong> — is to ensure that we avoid any weird <a href="https://developer.apple.com/swift/blog/?id=10">reference behavior</a>. In order to change any properties on our attributed string, we have to make a mutable copy. If instead we returned a mutable string, changing the properties on any second reference we create would also change the properties on the first. This can lead to unexpected behavior. I like that using a read-only attributed string here gives us an extra level of safety.</p><p>I really like the way this String -&gt; NSAttributedString conversion works. Let’s follow the same pattern, and add an extension to NSAttributedString that adds a UIColor attribute:</p><pre>extension NSAttributedString {<br>     func color(_ color: UIColor) -&gt; NSAttributedString {<br>          let mutableStr = NSMutableAttributedString(attributedString: self)<br>          let attributes = [<br>              NSAttributedStringKey.foregroundColor : color<br>          ]<br>          let range = NSRange(location: 0, length: self.length)<br>          mutableStr.addAttributes(attributes, range: range)<br>          return mutableStr<br>    }<br>}</pre><p>We now have a simple way of adding a color attribute to a string:</p><pre>someLabel.attributedText = &quot;Everybody dance&quot;<br>     .asNSAttributedString()<br>     .color(UIColor)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*Feslvtx3GDYhWFkBjoj4rA.png" /></figure><p>That’s really nice! It’s both concise and very obvious to anyone looking at our code as to what’s going on. But this doesn’t quite do what we want yet. What we need is a way to combine attributed strings. Let’s keep following the same pattern of extending our base class:</p><pre>extension NSAttributedString {<br>     func concat(_ attributedString: NSAttributedString) -&gt; NSAttributedString {<br>          let mutableStr = NSMutableAttributedString(attributedString: self)<br>           mutableStr.append(attributedString)<br>          return mutableStr<br>     }<br>}</pre><p>Now we can combine attributed strings:</p><pre>someLabel.attributedText = &quot;Everybody dance &quot;<br>     .asNSAttributedString()<br>     .concat(&quot;now! &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())<br>     .concat(&quot;duhn &quot;.asNSAttributedString())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*8w-NmYzVVPAQJtPLWZTgHQ.png" /></figure><p>And finally, we can easily and declaratively add attributes to each part of our final string:</p><pre>someLabel.attributedText = &quot;Everybody dance now!&quot;<br>     .asNSAttributedString()<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.yellow))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.blue))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.green))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.red))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.purple))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.orange))<br>     .concat(&quot;duhn &quot;<br>          .asNSAttributedString()<br>          .color(UIColor.brown))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*NoJfn02DN9NssbosonIHRw.png" /></figure><p>That’s infinitely cleaner and easier to read than the alternative. I was going to write out how you’d do this using just vanilla NSAttributedStrings — to show you how much uglier it would be — but honestly, I don’t even want to deal with that. I’ve only got so much time in my day, and I’ve gotta finish Breath of the Wild sometime in the next century.</p><p>I’ve only shown you how to add a UIColor attribute to an attributed string, but following the same pattern you could easily add functions for the other attributes that are available. There’s a lot you can do— you can change fonts, add strikethroughs, underline text and add a few other effects. I’ve considered making this a complete library and making it available on Github or as a CocoaPod, but I’ve already seen a few other CocoaPods out there that follow a similar approach. What are your thoughts? Leave them in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a31ba36b0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessive celebration!]]></title>
            <link>https://medium.com/@oleary.audio/accessive-celebration-2abdc595ad4?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2abdc595ad4</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Sun, 08 Oct 2017 18:45:37 GMT</pubDate>
            <atom:updated>2017-10-08T18:45:37.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>Access control basics in Swift</h4><p>Sometimes, when looking at a class or method you’ll see some modifiers in front of your declarations that look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ievWEob6SBBkoGKMngiZxQ.gif" /></figure><p>Just kidding. They’ll actually look like this:</p><pre>final class JusticeLeague {<br>   private func saveTheDay() {}<br>   static func punishCriminals() {}<br>}<br></pre><p>Final, private and static. You may have some idea what these mean. A final class is a class that cannot be sub-classed. A private function or property cannot be called upon outside of the immediate scope that it is declared in. (<a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html">Note that in Swift 4</a> the access level of a private function/property changed to include class extensions). A static function associates a function (or a property) to the class itself, rather than an instance of the class; meaning you would call the static function in the example above as JusticeLeague.punishCriminals().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3nzAyrkyZvxx8pQogpSQYA.jpeg" /></figure><p>So what advantage do we gain by using these access modifiers? Why would we bother declaring a class as final? Doesn’t it seem intelligent to keep open the possibility of subclassing everything? Doesn’t it add flexibility to be able to call every method outside of the scope of its initial declaration?</p><p>There are two main reasons why this is not the case. The first reason I’ll give you is less objective, but it’s super important. <strong>We don’t always want to allow access to every part of a class or method or property.</strong> A lot of times, especially when working on a large project or as part of a team, we want to “hide” the inner workings of a class or struct. We’ll provide methods that other parts of our code base can interact with, but we want to maintain the safety of certain properties or helper methods within the class. For example:</p><pre>class Gravitron {<br>   private let gravity: Double = 9.8</pre><pre>   func force(fromMass mass: Double) -&gt; Double {<br>      return mass*gravity<br>   }</pre><pre>}</pre><p>This might set a new record for my most contrived example, but hopefully you see what I’m talking about. Our Gravitron’s gravity property is some super secret science. We can’t let anyone else use it, otherwise they might screw it up. We don’t want to allow any other part of our code to have access to the amount of gravity that our Gravitron is going to apply to some mass, so we hide it as a private property.</p><p>The second reason for using access control is for performance. By default, when we declare a class or method, the Swift compiler assumes that at some point, we’re going to subclass or override our class or method. In order to do this, it Swift has to determine at runtime which method or property is being referred to. This is called <strong>dynamic dispatch</strong>. The benefit of this is obviously the flexibility given to the programmer to override a previously implemented block of code. The downside is that dynamic dispatch uses more resources than its alternative: <strong>static dispatch</strong>. When something is dispatched statically, the compiler already knows at runtime which method or class is being referred to, since this is the “final” instance of this particular element.</p><p>So those are the basics. Access control is important both from a performance standpoint and a “good code etiquette” standpoint. Plan ahead, and use access control when it makes sense. Party on!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6mfnXBxljPhgh-ekDRNxAw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2abdc595ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change the beats per minute in an audio clip? That sounds like a stretch…]]></title>
            <link>https://medium.com/@oleary.audio/change-the-beats-per-minute-in-an-audio-clip-that-sounds-like-a-stretch-e4ee3c1343d3?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4ee3c1343d3</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Thu, 28 Sep 2017 22:10:13 GMT</pubDate>
            <atom:updated>2017-09-28T22:10:13.189Z</atom:updated>
            <content:encoded><![CDATA[<h4>Audio time-stretch in Swift</h4><p>Let’s do something cool. I want to change the tempo of a piece of music so that it matches the beats per minute provided by a user. We’ll assume that we know the beats per minute of the unaltered piece of music. In fact, let’s pick a song that clocks in at exactly 120 beats per minute:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyURRmWtbTbo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyURRmWtbTbo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyURRmWtbTbo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41c0a44621c321dc0c47dc410cc1886/href">https://medium.com/media/a41c0a44621c321dc0c47dc410cc1886/href</a></iframe><p>There are a few main components to this. We need an instance of AVAudioEngine. The audio engine is a subclass of NSObject which contains a group of AVAudioNodes. An AVAudioNode is a base class which performs a certain type of operation within your audio chain. We’re going to need two nodes: an AVAudioPlayerNode, and AVAudioUnitTimePitch. The second of these two nodes is what does our time processing. Here’s the first block of code that I have in my view controller:</p><pre>var audioEngine = AVAudioEngine()</pre><pre>var playerNode = AVAudioPlayerNode()</pre><pre>let timeChange = AVAudioUnitTimePitch()</pre><pre>var bpm: Float = 120</pre><pre>@IBOutlet weak var slider: UISlider!</pre><pre>@IBOutlet weak var label: UILabel!</pre><pre>@IBOutlet weak var playButton: UIButton!</pre><p>In my ViewDidLoad function, I call a setup function:</p><pre>func setup() {<br>   label.text = &quot;120&quot;</pre><pre>   audioEngine.attach(playerNode)</pre><pre>   audioEngine.attach(changePitch)</pre><pre>   audioEngine.connect(playerNode, to: timeChange, format: nil)</pre><pre>   audioEngine.connect(changePitch, to: audioEngine.mainMixerNode, format: nil)</pre><pre>   audioEngine.prepare()</pre><pre>   do {<br>      try audioEngine.start()<br>   } catch {} <br><br>}</pre><p>This is how we connect audio nodes. We attach them to the audio engine, and then connect the nodes to each other, in order of processing. Now, to start the audio playback when the play button is tapped:</p><pre>@IBAction func playButtonTapped(_ sender: Any) {</pre><pre>   let url = Bundle.main.url(/service/forresource: &quot;dontStop&quot;, withExtension: &quot;.wav&quot;)</pre><pre>   if let url = url {<br>      do {</pre><pre>         let audioFile = try AVAudioFile(forReading: url)</pre><pre>         timeChange.rate = slider.value/bpm</pre><pre>         playerNode.scheduleFile(audioFile, at: nil, completionHandler: nil)</pre><pre>      } catch {<br>      }</pre><pre>   }</pre><pre>playerNode.play()</pre><pre>}</pre><p>Notice: timeChange.rate = slider.value/bpm</p><p>The “rate” property of timeChange is the value for the speed at which we play back audio. If we set it equal to the percentage of the slider value over the beats per minute of our song, we’re adjusting the tempo to a new beats per minute. Cool!</p><p>Now if we want to change the rate of playback at any point:</p><pre>@IBAction func sliderValueChanged(_ sender: UISlider) {<br>   label.text = String(sender.value)<br>   timeChange.rate = sender.value/bpm<br>}</pre><p>Finally, I want to add a “tap tempo” button, so the user can input a new tempo just by tapping. First, we add a date property to our view controller:</p><pre>var lastTap: Date? = nil</pre><p>Now, every time the button is tapped, we call this function:</p><pre>@IBAction func tappedTempo(_ sender: UIButton) {</pre><pre>   let currentTap = Date()</pre><pre>   if let lastTap = self.lastTap {</pre><pre>      let interval = currentTap.timeIntervalSince(lastTap)</pre><pre>      let newBpm = Float(60/interval)</pre><pre>      timeChange.rate = newBpm/bpm</pre><pre>      label.text = String(newBpm)</pre><pre>   }</pre><pre>   self.lastTap = currentTap</pre><pre>}</pre><p>So we get a time interval between each tap, and use that to calculate our new BPM. We could probably get a more accurate version of this if we average out a collection of taps over a period of time, but this will work as a demo.</p><p>There we have it! A way to lock in the playback rate of a piece of music to a new tempo. Pretty easy. <a href="https://github.com/pattypatpat2632/AudioBlogPost">Here’s the GitHub repo</a> if you want to check it out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4ee3c1343d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Custom[subscripting]]]></title>
            <link>https://medium.com/hackernoon/swift-custom-subscripting-a7c0af68e065?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c0af68e065</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Thu, 14 Sep 2017 22:56:07 GMT</pubDate>
            <atom:updated>2019-05-22T08:48:19.616Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re gonna take a break from talking about ReaktiveKit and Bond this week. I went down kind of a rabbit hole there with building our own Event and Observable classes, so this week we’re gonna go off topic a bit and talk about <a href="https://hackernoon.com/tagged/subscripting">subscripting</a> in <a href="https://hackernoon.com/tagged/swift">Swift</a>.</p><p>We use subscripts in Swift all the time, usually in an array or a dictionary. They look like this:</p><pre>someArray[2] = &quot;Some value&quot;<br>someDictionary[&quot;some key&quot;] = &quot;Some value</pre><p>You get the idea. We do all kinds of stuff with arrays and dictionaries. But what’s rad, is that we can add subscripting to our own custom classes and structs. The same way we can provide an initializer for our custom types, we can provide a subscript. Here’s a very simple example:</p><pre>struct Group {</pre><pre>   subscript(index: Int) -&gt; Int {<br>      get {<br>         return index<br>      }<br>   }<br>}</pre><pre>let justiceLeague = Group()<br>print(justiceLeague[3]) //prints &quot;3&quot;<br>print(justiceLeague[2]) //prints &quot;2&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DLAmNccuqWEQGHDB_kCOKw.gif" /></figure><p>That’s the very basics of how this works. Let’s ramp this up a bit and show how being able to subscript can be useful. In an app I published a little while back, I have a grid that is used to represent musical notes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*axaEJ1sukrQQ9J6_hGXzdw.png" /><figcaption><a href="https://itunes.apple.com/us/app/blipbloop/id1237810871?mt=8">BlipBloop</a></figcaption></figure><p>Each button represents a note, which in turn is represented by a struct. We’ll call that struct ‘Note.’ Here’s a simple implementation of Note:</p><pre>struct Note {<br>   let pitch: Int<br>   let isOn: Bool</pre><pre>   static let empty = Note(pitch: 0, isOn: false)<br>}</pre><p>Now what would be awesome is if there was a way to represent the grid of notes in a way that could be subscripted. So anytime we want to change a note on this grid, we could do something like this:</p><pre>grid[2, 3] = Note(pitch: 67, isOn: true)</pre><p>Here’s what a custom class that can represent our grid might look like:</p><pre>struct NoteMatrix{<br>   let rows: Int<br>   let columns: Int<br>   var grid = [Note]()</pre><pre>   init(rows: Int, columns: Int) {<br>      self.rows = rows<br>      self.columns = columns<br>      grid = Array(repeating: Note.empty, count: columns * rows)<br>   }</pre><pre>   subscript(row: Int, column: Int) -&gt; Note {<br>      get {<br>         return grid[(row * columns) + column]<br>      }<br>      set(newValue) {<br>         grid[(row * columns) + column] = newValue<br>      }<br>   }<br>}</pre><p>Now we can do this:</p><pre>var score = NoteMatrix(rows: 4, columns: 4)<br>score[2, 3] = Note(pitch: 67, isOn: true)</pre><pre>print(score[2, 3].pitch) //prints &quot;67&quot;</pre><p>Hey, wouldya look at that. We can also add an assert statement in the “get-set” part of our subscript that will crash everything if we reach outside of the number of rows and columns:</p><pre>assert(row &gt;= 0 &amp;&amp; row &lt; rows &amp;&amp; column &gt;= 0 &amp;&amp; column &lt; columns, &quot;Index out of range&quot;)</pre><p>Essentially we have the building blocks for creating collection types. I wanted to see if I could make this Matrix class work with generics, so I kind of hacked together something that… well it functions without any errors. It’s not pretty though. If you have some better ways to go about this, definitely let me know in the comments sections. Here it… ugh… here it is:</p><pre>struct Matrix&lt;T&gt;{<br>   let rows: Int<br>   let columns: Int<br>   var grid = [Int: [Int: T]]()</pre><pre>   init(rows: Int, columns: Int) {<br>      self.rows = rows<br>      self.columns = columns<br>   }</pre><pre>   subscript(row: Int, column: Int) -&gt; T? {<br>      get {<br>         assert(indexIsValid(row: row, column: column), &quot;Index out of range&quot;)<br>         if let gridRow = grid[row] {<br>            if let output = gridRow[column] {<br>               return output<br>            } else {<br>               return nil<br>            }<br>         }else {<br>            return nil<br>         }<br>      }</pre><pre>   set(newValue) {<br>      assert(indexIsValid(row: row, column: column), &quot;Index out of range&quot;)<br>         if let newValue = newValue {<br>            grid[row] = [column: newValue]<br>         }<br>      }<br>   }<br>   <br>   func indexIsValid(row: Int, column: Int) -&gt; Bool {<br>      return row &gt;= 0 &amp;&amp; row &lt; rows &amp;&amp; column &gt;= 0 &amp;&amp; column &lt; columns<br>   }</pre><pre>}</pre><pre>struct Note {<br>   let pitch: Int<br>   let isOn: Bool<br>}</pre><pre>var noteGrid = Matrix&lt;Note&gt;(rows: 4, columns: 4)</pre><pre>noteGrid[1, 1] = Note(pitch: 67, isOn: true)</pre><pre>print(noteGrid[1, 1]?.pitch) //prints &quot;67&quot;</pre><p>That’s gross. It definitely needs to be reworked. But now we have a generic Matrix that we can use with any custom type of ours. Seriously, if you have a better way to go about this, let me know. I have a feeling that to have a way to store values in a custom collection type, I have to go a bit further under the hood. But, anyway. Now you can see a bit how subscripting works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wICVyB5t0iLya87hPgGFYw.gif" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c0af68e065" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/swift-custom-subscripting-a7c0af68e065">Swift Custom[subscripting]</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactiveKit and Bond Part 1.3]]></title>
            <link>https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-3-d7cb83a910e8?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cb83a910e8</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Sun, 10 Sep 2017 01:19:01 GMT</pubDate>
            <atom:updated>2017-09-10T01:19:01.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>Observable properties</h4><p>If you’ve been following along my last couple of posts, I’ve been writing about how to use curried functions to implement the <a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-1-f6fd79d3bf84">Target-Action</a> pattern and create an <a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-2-fd1ec89b79ea">Event</a> class. This post will draw everything together, and show how to create observable properties on a class. If you haven’t checked out my post previous post on <a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-2-fd1ec89b79ea">events</a>, or read <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">this</a> post from the Scott Logic blog that I’ve linked to 100000000 times, you should do that in order to fully understand what I’m gonna be writing about here. After this post, we’ll have a pretty good understanding of how the Observer pattern can be carried out entirely in Swift, and we’ll be able to get back to talking about ReactiveKit and Bond.</p><p>First, what’s our goal here? What will an observable property in Swift look like? Well, we want a class whose properties that, when set to a new value, will send out an alert telling some other functions to be carried out. For example:</p><pre>class Batman {<br>   let numberOfSidekicks: Observable&lt;Int&gt;(0)<br>}</pre><p>Then when we implement this class:</p><pre>class VC: UIViewController {</pre><pre>   var bruceWayne = Batman()<br>   bruceWaye.numberOfSidekicks.updated.addHandler(self, handler:       VC.sidekicksChanged)</pre><pre>   func sidekicksChanged(oldValue: Int, newValue: Int) {<br>      if oldValue &gt; newValue {<br>         print(&quot;Oh no Batman! One of your sidekicks died! Typical.&quot;)<br>      } else {<br>         print(&quot;Batman! You have a new sidekick! We&#39;ll see how long that lasts.&quot;)</pre><pre>      }<br>   }<br>}</pre><pre><strong>//Then if something like this happens:</strong></pre><pre>bruceWayne.sideKicks += 1</pre><pre><strong>//the console prints out: &quot;Batman! You have a new sidekick! We&#39;ll see how long that lasts.&quot;</strong></pre><p>This is cool. We are having fun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*gSCWvralY6dw1LMY_jsUdw.gif" /></figure><p>So now let’s build the Observable class:</p><pre><strong>class</strong> <strong>Observable</strong>&lt;T&gt; {<br><br>  <strong>let</strong> didChange = Event&lt;(T, T)&gt;()<br>  <strong>private</strong> <strong>var</strong> <strong>value</strong>: T<br><br>  <strong>init</strong>(_ initialValue: T) {<br>    <strong>value</strong> = initialValue<br>  }<br><br>  func <strong>set</strong>(newValue: T) {<br>    <strong>let</strong> oldValue = <strong>value</strong><br>    <strong>value</strong> = newValue<br>    didChange.<strong>raise</strong>(oldValue, newValue)<br>  }<br><br>  func <strong>get</strong>() -&gt; T {<br>    <strong>return</strong> <strong>value</strong><br>  }<br>}</pre><p>Now we can build our Batman class from above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*cMrGtQYo-FvUEsVycJ5zGw.jpeg" /><figcaption>Batman!</figcaption></figure><p>I’ve lead us down the path where our observable properties on our class use the target-action pattern. Remember, our goal here is to turn this into a functional, reactive framework like ReactiveKit. We’re close: we’ve got the reactive part down but not really the functional part. How can we make these observable properties functional? I have an idea, but I think I’m gonna save that for next week. Feel free to leave your solutions below in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cb83a910e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpinnerBot Support Page]]></title>
            <link>https://medium.com/@oleary.audio/spinnerbot-support-page-d9d3ec7bcc76?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d3ec7bcc76</guid>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 14:25:39 GMT</pubDate>
            <atom:updated>2017-09-08T14:25:39.179Z</atom:updated>
            <content:encoded><![CDATA[<p>For SpinnerBot support, email spinnerbottheapp@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d3ec7bcc76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactiveKit and Bond Part 1.2]]></title>
            <link>https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-2-fd1ec89b79ea?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1ec89b79ea</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Sun, 03 Sep 2017 01:57:10 GMT</pubDate>
            <atom:updated>2017-09-03T01:57:10.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>Events in Swift</h4><p>Sorry for the late publish this week; I hurt my leg running last week and I’ve been on some strong medication. Also, <a href="http://www.espn.com/blog/baltimore-orioles/post/_/id/1628/brainy-birds-why-the-orioles-are-smarter-than-us-all">the Orioles suddenly started winning again</a>, so my evenings have become a little busier. I’ve been writing about implementing reactive elements in Swift, like what we see in <a href="https://github.com/ReactiveKit/ReactiveKit">ReactiveKit</a> and <a href="https://github.com/ReactiveKit/Bond">Bond</a>. Up until now, we’ve mostly been implementing the Observer pattern using out of the box, first class Swift methodologies like Delegation and <a href="https://medium.com/@oleary.audio/i-am-the-key-value-observing-master-2aa3fc5de53d">KVO</a>. Earlier this week, I went a bit further and showed Swift implementation of the <a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-1-f6fd79d3bf84">Target-Action</a> pattern. Today, we’re going to talk about Events.</p><p>Events are a way to assign some functions to be carried out when another method is fired off. It should have an array of functions, a way to add those functions to that array, a way to remove those functions from the array, and a method that calls on each of the stored functions. Here’s a simple implementation of an Event class, borrowed from a post by <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">Colin Eberhardt</a>:</p><pre>class Event {<br><br>  private var eventHandlers = [() -&gt; ()]()<br><br>  func addHandler(handler: () -&gt; ()) {<br>    eventHandlers.append(handler)<br>  }<br><br>  func raise() {<br>    for handler in eventHandlers {<br>      handler()<br>    }<br>  }<br>}</pre><p>We can make our handlers capable of taking in parameters by using generics:</p><pre>class Event&lt;T&gt; {<br>   private var eventHandlers = [(T) -&gt; ()]()<br>   <br>   func addHandler(handler: @escaping (T) -&gt; ()) {</pre><pre>      eventHandlers.append(handler)</pre><pre>   }<br>   <br>   func raise(data: T) {<br>      for handler in eventHandlers {<br>         handler(data)<br>      }<br>   }<br>}</pre><p>Now we can do something like this:</p><pre>let event: Event&lt;Int&gt; = Event()</pre><pre>event.addHandler { (num) in<br>   print(num)<br>}</pre><pre>event.addHandler { (num) in<br>   print(num + 1)<br>}<br>event.raise(data: 10)</pre><pre>//prints &quot;10&quot;<br>//prints &quot;11&quot;</pre><p>You can start to see how this is building towards an observable property. We have a collection of events that will occur every time we fire off a function. Say we did this:</p><pre>class Batman {<br>   var criminalsBiffed: Int = 0 {<br>      didSet {<br>         batEvent.raise(data: criminalsBiffed)<br>      }<br>   }<br>   <br>   let batEvent: Event&lt;Int&gt; = Event()<br>}</pre><pre>let bruceWayne = Batman()<br>bruceWayne.batEvent.addHandler { (num) in<br>   print(num)<br>}</pre><pre>bruceWayne.criminalsBiffed += 1<br>//&quot;1&quot; will be printed out</pre><p>As you can see, we have the beginnings of an observable class. What’s more, unlike KVO where we’re dependent on an Objective-C code base, we’re building entirely in Swift. This means we can use Swift value types like Enums. We’re also keeping our code clean and type safe. Dope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*2LGjaQTazqtIJ0geCXB1zg.gif" /><figcaption>I use too many John Oliver gifs.</figcaption></figure><p>There are still some problems here though. First of all, we’re at risk for memory leaks if any of our handlers capture an instance of ‘self.’ Not a huge deal, all you have to do is add [weak self] to the capture list for each closure where this could occur. But that can be pretty easy to forget to do, and it’s a risk that’d be nice to avoid.</p><p>We also don’t have any way to remove handlers. As <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">Colin</a> points out, this is because Swift closures don’t conform to the AnyObject protocol, meaning there’s no way to compare them to each other in order to remove them from the ‘eventHandlers’ array.</p><p>The solution to this problem is to create a wrapper for the event handlers, with a curried function. This is similar to what we did in implementing the <a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-1-f6fd79d3bf84">Target-Action</a> pattern.</p><p>Again, I’m using the code directly from <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">Colin</a> Ebarhardt, (seriously, <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">read his article</a>)but I want to walk you through step by step to see if we can get a handle on what’s going on here.</p><pre>class EventHandlerWrapper&lt;T: AnyObject, U&gt;<br>                                  : Invocable, Disposable {<br>  weak var target: T? <br><strong>//OK, we have a target. This is how we&#39;re going to get a weak reference to &#39;self&#39; later down the line, without having to add it to a capture list.</strong></pre><pre>  let handler: T -&gt; U -&gt; () <br><strong>//Here&#39;s our curried function - thing of this as &#39;a function that takes an argument of type T as a parameter, returns another fucntion that takes in and argument of type U as a parameter, which returns Void</strong><br>  let event: Event&lt;U&gt; <br><strong>//We&#39;ll define this class in a bit. Note that the generic type &#39;U&#39; matches the 2nd parameter type of the curried function T -&gt; U -&gt; ()</strong><br><br>  init(target: T?, handler: T -&gt; U -&gt; (), event: Event&lt;U&gt;) {<br>    self.target = target<br>    self.handler = handler<br>    self.event = event;<br>  }<br><br>  func invoke(data: Any) -&gt; () {<br>    if let target = target { <strong>//This will execute the curried function</strong><br>      handler(target)(data as U) <strong>//We&#39;re calling the curried function, which had the target defined earlier, with whatever data has been provided</strong></pre><pre>    }<br>  }<br><br>  func dispose() { <strong>//This will remove the event handler</strong><br>    event.eventHandlers =<br>       event.eventHandlers.filter { $0 !== self }<br>  }<br>}<br><br>public protocol Disposable {<br>  func dispose()<br>}</pre><pre>public protocol Invocable: class {<br>  func invoke(data: Any)<br>}</pre><p>Now, we can define an Event type that avoids memory leaks, and has a way to remove handler functions: (Once again, credit to <a href="http://blog.scottlogic.com/2015/02/05/swift-events.html">Colin Eberhardt</a>)</p><pre>public class Event&lt;T&gt; {<br><br>  public typealias EventHandler = T -&gt; ()<br><br>  private var eventHandlers = [Invocable]() <strong>//Rather than defining our eventHandlers as an array of EventHandler, they are now an array of any type that conforms to the Invocable protocol above. This is because now we&#39;re putting each handler within a wrapper, in order to get a reference to our Target</strong></pre><pre>  public func raise(data: T) { <br>  for handler in self.eventHandlers {<br>    handler.invoke(data)<br>    }<br>  }<strong>//Similar to the original Event class, we have a function that fires off all the handler functions in eventHandlers. Remember though, our new eventHandlers are not just vanilla functions. They&#39;re wrapped as curried functions.</strong></pre><pre><br>  public func addHandler&lt;U: AnyObject&gt;(target: U,<br>            handler: (U) -&gt; EventHandler) -&gt; Disposable {<br>    let wrapper = EventHandlerWrapper(target: target,<br>                         handler: handler, event: self)<br>    eventHandlers.append(wrapper)<br>    return wrapper<br>  } </pre><pre>}</pre><p>Now we have a fully implementable Event class:</p><pre>class BatController: UIViewController {<br><br>  <em>// create an event<br></em>  <strong>let</strong> <strong>event</strong> = Event&lt;(String)&gt;()<br><br>  <em>// add a handler<br></em>  <strong>let</strong> handler = <strong>event</strong>.<strong>addHandler</strong>(self, ViewController.handleEvent)<br></pre><pre>func <strong>handleEvent</strong>(data: (String)) {<br>  <strong>println</strong>(data)<br>}<br>}</pre><p>Now, anytime call event.raise(“Something”), something gets printed to the console. To stop this from happening, we can call event.dispose()</p><p>That’s it for this week. I was kinda hoping to get a little more in depth about this, but as they say in France: time’s a wastin’. Next week we’re finally gonna draw this all together and demonstrate how to make a Swifty, observable property. It’s gonna be so sweet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1ec89b79ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactiveKit and Bond Part 1.1]]></title>
            <link>https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-1-f6fd79d3bf84?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6fd79d3bf84</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Tue, 22 Aug 2017 15:09:34 GMT</pubDate>
            <atom:updated>2017-08-22T15:10:00.517Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Target-Action pattern in Swift</h4><p><a href="https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-dc13a7d99f96">In my last post</a>, I promised to get into a little bit of how the sausage gets made in reactive frameworks, in order to better understand what’s going on in ReactiveKit and Bond. This is going to be a multi-step process, and the first step is understanding the target-action pattern, and how to implement it in Swift. I am going to borrow heavily from <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/">Ole Begemann’s post</a> on this topic. <a href="https://www.objc.io/books/advanced-swift/">If you’ve never checked out the book he wrote with Chris Eidhof, I one hundred-thousand percent recommend it</a>.</p><p>Here’s a weird/cool thing about Swift: you can create a reference to a method, and call that method later, using an instance of the class that method belongs to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*zbcnzH9kWwsWNfvh4Jgmlg.gif" /><figcaption>“OK Pat, you’ve lost me.”</figcaption></figure><p>Here Mark Wahlberg, let me show you what I mean. Ole uses a “bank account” class to explain this, but that’s boring. We’re gonna use a Batman class:</p><pre>class Batman: {</pre><pre>   var criminalsBiffed: Int = 0</pre><pre>   func biffCriminals(amount: Int) {<br>      criminalsBiffed += amount</pre><pre>   }</pre><pre>}</pre><pre>let bruceWayne = Batman()<br>bruceWayne.biffCriminals(amount: 2)<br>print(bruceWayne.criminalsBiffed)<br>// prints &quot;2&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_oF6D6DAITaBkuAQFxf_w.jpeg" /></figure><p>Ok. Super easy. Now here’s the tricky part. Let’s create a reference to criminalsBiffed(amount: Int)</p><pre>let biffer = Batman.biffCriminals</pre><p>“biffer” is not a call to a method. It’s a constant that refers to the method Batman.biffCriminals. Biffer has a type of (<a href="/service/apple-reference-documentation://hsKdp31_M6">Batman</a>) -&gt; (<a href="/service/apple-reference-documentation://hsf4N66ABq">Int</a>) -&gt; (). We can then create a new reference, which takes an instance of Batman as a parameter:</p><pre>let wayneBiffer = biffer(bruceWayne)</pre><p>Then we can call on the new method with a parameter:</p><pre>wayneBiffer(amount: 10)<br>print(bruceWayne.biffedCriminals)<br>//now prints out &quot;12&quot;</pre><p>This can be shortened to one line:</p><pre>biffer(bruceWayne)(amount: 10)</pre><p>This is what is called a curried function. A function is partially applied, with some of the parameters set before the final method is called. When we curry a function, we are returning another partially fulfilled function.</p><p>Where this becomes really useful is in implementing the Target-Action pattern in a type safe way. Target-Action is a nice, semi-reactive way to carry out a callback after an event has occurred. As Ole points out, it can be an improvement over using closures because it forces you to deal with any strong and weak references at the point of implementation, rather than leaving these to be dealt with when the function is called.</p><p>You see the Target-Action pattern all the time when dealing with UI elements:</p><pre>let button = UIButton()<br>button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)</pre><pre>func buttonTapped() {<br>   print(&quot;Button tapped!&quot;)</pre><pre>}</pre><p>The #selector is there because this implementation of Target-Action is dependent on Objective-C . We can make this type safe in Swift. Here is <a href="https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/">Ole</a>’s implementation of Target-Action, with my own comments added:</p><pre>protocol TargetAction {<br>    func performAction()<br>}</pre><pre>struct TargetActionWrapper&lt;T: AnyObject&gt; : TargetAction {<br>    weak var target: T?</pre><pre><strong>//Here&#39;s our curried function<br>   </strong>let action: (T) -&gt; () -&gt; ()<br><br>    func performAction() -&gt; () {<br>        if let t = target {<br>            action(t)() <strong>//when performAction is called, we&#39;re calling on the curried function stored in the TargetActionWrapper</strong><br>        }<br>    }<br>}<br><br>enum ControlEvent {<br>    case touchUpInside<br>    case valueChanged<br>    // ...<br>}<br><br>class Control {<br>  <strong> // This dictionary will store the actions for each control event</strong><br>   var actions = [ControlEvent: TargetAction]()</pre><pre><strong>//Adds a target and links it to an action</strong><br>    func setTarget&lt;T: AnyObject&gt;(target: T, action: (T) -&gt; () -&gt; (), controlEvent: ControlEvent) {<br>        actions[controlEvent] = TargetActionWrapper(target: target, action: action)<br>    }<br><strong>//Removes a target</strong><br>    func removeTargetForControlEvent(controlEvent: ControlEvent) {<br>        actions[controlEvent] = nil<br>    }</pre><pre><strong>//This function should be called when an event occurs - e.g. a button tap</strong><br>    func performActionForControlEvent(controlEvent: ControlEvent) {<br>        actions[controlEvent]?.performAction()<br>    }<br>}</pre><p>So let’s do some refactoring to see how this works. Here’s an API Client class, with a function to get a token from the API:</p><pre>final class ApiClient {</pre><pre>//init, declare properties etc.</pre><pre>func getToken(completion: @escaping (String) -&gt; Void) {<br>   let endpoint = &quot;https://token.endpoint&quot;</pre><pre>   guard let url = URL(string: endpoint) else { return }<br>   var request = URLRequest(url: url)<br>   let session = URLSession(configuration:<br>   URLSessionConfiguration.default)<br>   let task = session.dataTask(with: request) { (data, response, error) in<br>   if let data = data {<br>      do {<br>            //parse data to get token<br>            completion(token)<br>         } catch {}<br>      } else {}<br>   }<br>   task.resume()<br>}</pre><pre>}</pre><p>Here’s how this would be refactored for Target-Action.</p><pre>final class ApiClient: <strong>Control</strong> {</pre><pre>//init, declare properties etc.<br><strong>var token: String?</strong></pre><pre>func getToken(completion: @escaping (String) -&gt; Void) {<br>   let endpoint = &quot;https://token.endpoint&quot;</pre><pre>guard let url = URL(string: endpoint) else { return }<br>   var request = URLRequest(url: url)<br>   let session = URLSession(configuration:<br>   URLSessionConfiguration.default)<br>   let task = session.dataTask(with: request) { <strong>[weak self]</strong>(data, response, error) in<br>   if let data = data {<br>      do {<br>            //parse data to get token  <br>            <strong>self.token = token</strong>                    <br>            <strong>self.performActionForControlEvent(controlEvent: .tokenReceived)</strong><br>         } catch {}<br>      } else {}<br>   }<br>   task.resume()<br>}</pre><pre>}</pre><p>Now, in our view controller where we need to get our token:</p><pre>class ViewController: UIViewController {</pre><pre>   let apiClient = ApiClient()</pre><pre>   override func viewDidLoad() {<br>      super.viewDidLoad()<br>      <strong>apiClient.setTarget(target: self, action:<br>LoginViewController.printToken, controlEvent: .tokenReceived)<br>      apiClient.getToken()</strong></pre><pre>   }<br>   func printToken() {<br>      print(apiClient.token)<br>   }</pre><pre><br>}</pre><p>So there you have it. As I mentioned before, this is nice in that it gets rid of the need to deal with reference cycles in the upper levels of our code. Next time, we’ll see how this gets us closer to reactive programming. Any thoughts? Leave ’em below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6fd79d3bf84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactiveKit and Bond Part 1]]></title>
            <link>https://medium.com/@oleary.audio/reactivekit-and-bond-part-1-dc13a7d99f96?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc13a7d99f96</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Thu, 17 Aug 2017 16:48:10 GMT</pubDate>
            <atom:updated>2017-08-17T16:48:10.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dr. No (way am I not gonna tell you about ReactiveKit)</h4><p>Last week I discussed the MVVM architecture and the basics of how to implement it. If you remember, I explained that developers working in MVVM will commonly employ a reactive framework when working within the architecture. Today, we’re going to take a quick look at some of the basics of one of these frameworks: <a href="https://github.com/ReactiveKit/ReactiveKit#cocoapods">ReactiveKit</a>.</p><p>ReactiveKit is actually split into two parts. The main part, ReactiveKit itself, is the core of the framework. <a href="https://github.com/ReactiveKit/Bond">Bond</a> is the second part. Bond sits on top of ReactiveKit and provides reactive “bindings” for UIKit. Bond can be used alone as a way to manage state changes, or if you’re building your core reactively with ReactiveKit, it provides a way to link between that core, and the more Object-Oriented UIKit.</p><p>To see how Bond works, let’s start with the example they give. Let’s say we wanted to instantly display whatever a user types into a search bar, in a label. Here’s how we would do this in vanilla Swift:</p><pre>override func viewDidLoad() {<br>   super.viewDidLoad()<br>   <strong>textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)</strong><br>}</pre><pre><strong>func textChanged() {<br>   label.text = textField.text<br>}</strong></pre><p>Pretty straightforward. But as you start adding UI elements and your view controller grows, it might start to get a little ugly having your targets and functions all in separate parts of your code. Here’s what this looks like in Bond:</p><pre>override func viewDidLoad() {<br>   super.viewDidLoad()<br>   <strong>textField.reactive.text.observeNext { text in<br>      self.label.text = text<br>   }</strong><br>}</pre><p>Cool! Everything is all in one place. And it’s very clear exactly what’s happening here. What’s even better, is Bond includes some nice, Swifty sugar to make this even easier to read:</p><pre>textField.reactive.text.bind(to: label.reactive.text)</pre><p>As the Bond documentation points out, because binding to a label text property is so common this can be shortened further:</p><pre>textField.reactive.text.bind(to: label)</pre><p>That’s it. One line. And we haven’t lost any readability. If anything, we’ve made it easier for someone looking at our code to tell what’s going on.</p><p>Now here’s where the functional part of this comes in. Say we wanted the label to only display in uppercase letters:</p><pre>textField.reactive.text.map{$0?.uppercased()}.bind(to: label)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*hR-xN0zxVhkMms_A0jL62Q.png" /><figcaption>Yes. Very rad.</figcaption></figure><p>Most UIKit objects have Bond extensions. The easiest way to find them is to add .reactive to an object in Xcode and see what comes up in the list.</p><p>So here’s where this starts to become really handy. <a href="https://medium.com/@oleary.audio/i-like-to-mvvm-it-mvvm-it-4d8004d79769">Remember last week when I was talking about MVVM</a>? I talked a bit how there wasn’t a perfect “out of the box” solution for enacting communication between your view and view-model and model. Key-Value Observing can be ugly and unwieldy. Using the delegate pattern overrides the independence we were seeking between each segment of MVVM. A reactive functional framework like Bond takes the best principles of KVO and makes it super easy to use:</p><pre>viewModel.dogName.map{$0.uppercased()}.bind(to: label)</pre><p>So now, as dogName is updated in the view model, the label will automatically update to the new dogName. This works just like KVO, but without any of the messy Objective-C leftovers, or without having to make a big switch statement in your observeValue() function.</p><p>I should make a note here that reactive programming has some of its own conventions for formatting. For instance, the example above would normally be written like this:</p><pre>viewModel.dogName<br>   .map{$0.uppercased()}<br>   .bind(to: label)</pre><p>Visually that’s a little more clear. Especially when you start adding functional extensions to the properties you’re binding.</p><p>So let’s say we build ourselves a view model. How do we make it so that the properties of the view model can be bonded? Super easy. Bond gives us a new type called Observable. It essentially acts as a wrapper for a primitive type property that we want to observe. To declare an observable property, we declare it as type Observable&lt;PropertyType&gt;, with some initial value. For example:</p><pre>struct Dog {<br>   var dogName: Observable&lt;String&gt; = Observable(&quot;Maizie&quot;)<br>}</pre><p>Swift can infer the type here so this can be shortened to:</p><pre>var dogName = Observable(&quot;Maizie&quot;)</pre><p>Now dogName can be bonded.</p><pre>dog.dogName.bind(to: label)</pre><p>So there we have it. The very basics of ReactiveKit and Bond. Obviously there’s a lot more to this, and I’ll be continuing this topic next week. I also want to go a bit more into how the sausage is being made here. Practically, this feels like a refined version of Key-Value Observing. Is there an alternative, Swifty way to implement KVO? (Hint: there is!) Leave comments. Party on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc13a7d99f96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I like to MVVM it MVVM it]]></title>
            <link>https://medium.com/@oleary.audio/i-like-to-mvvm-it-mvvm-it-4d8004d79769?source=rss-7d9a4d5eb30e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8004d79769</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Patrick O'Leary]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 19:00:02 GMT</pubDate>
            <atom:updated>2017-08-09T19:04:06.662Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of my writing about code involves the smaller aspects of building an app. Things like cool frameworks, idiomatic Swifty things. Not a mention of the overall way to structure a project. Today, that changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*NwsGNSIQgNtcM9QpqaQvDw.gif" /><figcaption>Ch ch ch… changes!</figcaption></figure><p>There are several common design patterns for the overall structure of an app. Model-View-Controller is the simplest and probably most common. You have a view, which represents the user interface, a controller, which controls the logic of the UI, and a model, which represents an object or some data. The view talks to the controller which talks to the model. The model and the view are never in direct communication. This is great, but the downside is that a lot of the logic is handled by the controller. The often results in massive amounts of code within our View Controllers, and can lead to confusion about which part of your program is responsible for which part of the logic. This is where MVVM comes in.</p><p>MVVM stands for Model-View-ViewModel. It adds an extra step of abstraction in between your model and the view controller. In this pattern, your views talk to the view controller, as before in MVC, letting the VC know of any user interaction. The view controller then talks to a <strong>view model</strong>, which in turn talks to the model. In this case, all of the business logic is removed from the view controller and placed in the view model. The controller now just has two jobs: to inform the view model when a user interaction has occurred within a view, and to inform the views when to update, using the data provided to it by the view model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*MPu7qeuv_Fjtc2iGdLlZtA.png" /><figcaption>Dig it!</figcaption></figure><p>So those are the basics. Next is to figure out a way to get each of these steps — the model, view model, and view/view controller — to talk to each other. One common way is to use a Functional Reactive Programming framework. FRP is way beyond the scope of this week’s post, so I won’t go into it. It’s a very cool way to think about coding, so if you’re interested, you should definitely check out <a href="https://github.com/ReactiveCocoa/ReactiveSwift">ReactiveSwift</a> and <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>. I also just came across <a href="https://github.com/ReactiveKit/ReactiveKit">ReactiveKit</a>, which seems to be a little more lightweight, and possibly a little easier to jump into if you haven’t seen reactive programming before. I’ve been looking for an excuse to get into a reactive framework, and I may just have found it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zEMga83oD72c6GIusSfcWw.gif" /><figcaption>Just jump right in!</figcaption></figure><p>Another way to get your view/view model/model components to talk to each other is through Key-Value Observing. <a href="https://medium.com/@oleary.audio/i-am-the-key-value-observing-master-2aa3fc5de53d">I talked about KVO last week</a>. We establish our models as having observable properties, and add observers to those properties onto our view models. The view models then perform whatever logic is necessary on the properties, then they themselves will update some observed property, which the view controller is observing. The method has some definite pros and cons. On the plus side, you maintain a high level of independence between each layer of your MVVM architecture. Your classes/structs will be very self contained and easy to test. The downside to this is that KVO in Swift inherits a lot of ugliness from Objective-C. While it did significantly improve in Swift 3, and more improvements are coming in Swift 4, the syntax feels unwieldy compared to most operations in Swift. Personally, I think the pros far outweigh the cons, but you’ll frequently hear developers complaining about using KVO in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*jW84EG55cXKFhtft02QHJQ.gif" /><figcaption>I don’t want to write KVO!</figcaption></figure><p>A third option — albeit one that I haven’t seen too many developers use in MVVM — is to use the delegate pattern to implement MVVM. If you are unfamiliar with the delegate pattern using protocols, <a href="https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef">here’s a good summary I found</a>. Your view model will have an instance of the model it’s using for information. The view model declares itself as a delegate of the model. Anytime the model updates, it fires off a function that is declared in the ‘ModelDelegate’ protocol, and implemented within the view model. The same relationship happens between the view model and the view controller. Delegation also has some pros and cons. A big con is that you’re very deliberately coupling the model to the view model, and the view model to the view controller. This takes away some of the independence of each level of the architecture. You’re forced to be very deliberate about when to update the views. The separation of logic becomes less clear, which slightly defeats the purpose of using MVVM in the first place. The benefit of using delegation is that protocol oriented programming is one of the things that Swift is all about. The syntax is simple, and it’s hard to misread what your intent is.</p><p>So now that we have the basics of MVVM down, I’ve built a project for you to glance over if you want to see how this actually works. It’s probably easier to read if you see it in an actual project, <a href="https://github.com/pattypatpat2632/KVOBlogPost">so here’s a link to the github repo</a>. All I’ve done is take last week’s example on KVO, and refactored it using MVVM architecture. The Model and View Model communicate via KVO, while the View Model and View Controller communicate through the delegate pattern.</p><p>So that’s MVVM! I think it’s a good way to structure a project. As always, leave any questions or comments below, and I hope you have a rad week!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8004d79769" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>