<?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 Tom Zurkan on Medium]]></title>
        <description><![CDATA[Stories by Tom Zurkan on Medium]]></description>
        <link>https://medium.com/@tomzurkan?source=rss-bf76af7c6eae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8TYeOk2xL5fRQdN3HGaWcw.jpeg</url>
            <title>Stories by Tom Zurkan on Medium</title>
            <link>https://medium.com/@tomzurkan?source=rss-bf76af7c6eae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:52:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomzurkan/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[O.G. O.C.]]></title>
            <link>https://tomzurkan.medium.com/o-g-o-c-be8bbcbf3df0?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/be8bbcbf3df0</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 00:13:05 GMT</pubDate>
            <atom:updated>2023-09-08T00:13:05.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DR8GO0tNA-065VXvyVPNHw.jpeg" /></figure><p>Objective-C has been around for a while and I love working with it. My one complaint is it is so verbose (lots of typing). But, the verbosity has named parameters. That feature didn’t seem to come into other languages till later. What else makes Objective-C O.G.?</p><p>Objective-C was developed in the 1980’s and was used by Steve Jobs company NextStep. NextStep was eventually bought by Apple and OSX was born. As a matter of fact, you may not know that the prefix NS is from NextStep. And of course Next Steps OS was based on the mach micro kernel (unix).</p><p>The most obvious Objective-C feature is the optional. You can access an optional method with brackets as in <strong>[object method]</strong>. If the object is nil, the method is a noop (no operation). This really makes code look nice and clean with less checking for nil every statement. The equivilant of optional chaining.</p><p>Another feature I might point to would be the literal. Ok, so you have literal string with @”here”. But, you can also use that for other literals like dictionaries, lists, and NSInteger:</p><p><strong>NSArray *arr = @[@”1&quot;, @”2&quot;, @”3&quot;];</strong></p><p><strong>NSDictionary *dict = @{@”1&quot;:@1, @”2&quot;:@2, @”3&quot;:@3};</strong></p><p>That is pretty convenient and simple don’t you think?</p><p>So, those are a couple of interesting features but let’s go deeper. We can’t forget about ARC (automatic reference counting). That might sound trivial, but, it is pretty awesome to not have to keep track of “ownership” through reference counting. It’s definitely one of the cooler features of Objective-C.</p><p>But, there’s more. I have always said about Java that things like access modifiers are more suggestions than ridgid rules. You can use reflection to modify those modifiers. Objective-C also gives you flexibility. It has class method addition as well as something called swizzling where you can actually replace the functionality of an existing method in a class.</p><p>Below I have provide a simple example of taking a vanilla object and using something called the associated object, you can essentially add getters and setters. Below, I just used methods to make it easy. I also added them in the init which isn’t ideal.</p><pre>NS_ASSUME_NONNULL_BEGIN<br><br>@interface Player : NSObject<br><br>@end<br><br>NS_ASSUME_NONNULL_END</pre><pre>#import &quot;Player.h&quot;<br>#import &lt;objc/runtime.h&gt;<br><br>@implementation Player<br>- (instancetype)init {<br>    if (self = [super init]) {<br>        // Initialize self<br>        //Class clazz = objc_allocateClassPair(self, &quot;Player2&quot;, 0);<br>        BOOL v = class_addMethod([self class], @selector(setMyObject), (IMP) setMethodIMP, &quot;v@:@&quot;);<br>        v = class_addMethod([self class], @selector(getMyObject), (IMP) getMethodIMP, &quot;@@:&quot;);<br><br>        <br>    }<br>    return self;<br>}<br>void setMethodIMP(id self, SEL _cmd, id val)<br>{<br>    // implementation ....<br>    objc_setAssociatedObject(self, &quot;myNewObject&quot;, val, OBJC_ASSOCIATION_RETAIN);<br>}<br><br>id getMethodIMP(id self, SEL _cmd)<br>{<br>    // implementation ....<br>    return objc_getAssociatedObject(self, &quot;myNewObject&quot;);<br>}<br>- (void)dealloc {<br>    objc_removeAssociatedObjects(self);<br>}<br>@end</pre><p>I took a vanilla object and added a method for setting and getting a new object. The associated object is a associated map that comes with each NSObject and allows you to add variables by using the associated map along with augmenting the class.</p><pre>    Player *p = [[Player alloc] init];<br>    <br>    SEL sel = @selector(setMyObject);<br>    NSString *str = @&quot;Objective-C is powerful !&quot;;<br>   <br>    [p performSelector:sel withObject:str];<br>    <br>    id val = [p performSelector:@selector(getMyObject)];</pre><p>Since runtime supports performSelector, you can call methods at runtime by name without knowing much about the actually class or object. As you can see above, the performSelector can be used to call methods that have been added at runtime. Pretty cool!</p><p>You can also use categories to create extensions for existing classes. The category basically adds the method to the class at compile time instead of runtime. But, you could see how you could use associated objects along with categories to add some neat features to classes in other packages.</p><p>There are also key value observing that can be added at the NSObject level to be notified when an objects key value has changed. The key value observer pattern is a very powerful feature.</p><p>Lastly, let’s not forget blocks as objects (They are like functions but can be assigned to variables and passed as arguments). The completion handler is a pretty constant pattern in Objective-C.</p><p>As I had mentioned earlier, one of my complaints about Objective-C is it can be very verbose. But, that is also one of its strengths. You have named parameters which makes readability and parameter information pretty straight forward.</p><p>I’ve listed quite a few things about Objective-C that make it the original. You can do alot with Objective-C. But, with great power comes great responsibility. You can definitely run into problems if you misuse it. If you haven’t taken Objective-C for a spin, try the language out, you may find it a great gateway to C. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be8bbcbf3df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Heap/Priority Queue]]></title>
            <link>https://tomzurkan.medium.com/swift-heap-priority-queue-6a1644ba8d5d?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1644ba8d5d</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[priority-queue]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 19:08:29 GMT</pubDate>
            <atom:updated>2023-07-25T19:08:29.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was developing a scheduler in Swift and came across the fact that Swift does not provide a priority queue. So, then I looked up what it took to implement a <a href="https://en.wikipedia.org/wiki/Priority_queue">priority queue</a> which lead me to the <a href="https://en.wikipedia.org/wiki/Heap_(data_structure)">heap</a> implementation. The reason the heap implementation is interesting is because it gives a Big O Notation of O(1) for getting the top element and a O(log n) on insert and remove. As it turns out, implementation is very easy and maybe that is why there is not a default implementation. First, let’s start with a picture of the implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*mO3axc1Bo9tEzSDXAZURHg.png" /></figure><p>Above you can see the tree and how it is represented in an array. So, this means there are a couple of properties to our array that make it a heap or graph. We have a pattern of node, left leaf, right leaf, left leaf of left…. This means that:</p><p>the parent can be found by :</p><p>parent = (index-1)/2</p><p>So, for left leaf (19 in the figure above) it would be (1–1)/2 is our parent. For left leaf of left (17 in the figure above), it would be (3–1)/2 or index 1.</p><p>the reverse can be used to find the children:</p><p>left = index * 2+1</p><p>right=index*2+2</p><p>So, using these simple rules, we can create a heap in Swift like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a73baff30e869a2af3b5da757be34265/href">https://medium.com/media/a73baff30e869a2af3b5da757be34265/href</a></iframe><p>A couple of things to note: I haven’t set everything private for demonstration purposes. Also, this heap keeps the array and maintains its count. Since we set the first element as the last element during delete, we can also safely call remove on the last element of the array at no cost (i.e. no shift necessary).</p><p>So, the above code achieves a heap queue that always returns the top most item based on the comparator. We could easily flip around our comparator and create a min heap. As you can see, we achieve our O(log n) where n is the length of the array heap in our Heap class. Getting the top element is O(1). The insert is essentially adding something to the end and then walking up its parent to find the right spot and since the parent is halved every time, we will get at most a log n times of walking.</p><p>The same is true for the removal, we replace the top with the bottom and then rebalance the tree.</p><p>I hope this helps you to either use the priority queue or create your own. The priority queue or heaps can be useful for both backend and frontend Swift. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1644ba8d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye completion handlers and Dispatch.main.async.]]></title>
            <link>https://tomzurkan.medium.com/goodbye-completion-handlers-and-dispatch-main-async-76431c23baad?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/76431c23baad</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 19:04:31 GMT</pubDate>
            <atom:updated>2023-07-25T19:04:31.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImJyPIRNLiLXjGSfJQl_dA.png" /></figure><p>I may be a little late to this party. But, I was implementing an application and started to use the old tried and true completion handler approach. After I had completed the task, I looked over the work again and wondered what it would take to convert to async await. Not only was it trivial to convert, it looks so much cleaner I had to say goodbye to completion handlers. Of course, if you still need to maintain compatability with Objective-C then you will have to wait. If you are providing APIs, I still feel like it is a good idea to provide both options like URLSession does.</p><p>So, let’s take a look at what the old style of code looks like on a view controller. Of course, if you are using SwiftUI then the allure for async await should be too much to bare. But, if you have some old code or are still using UIKit, read on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce9d7fa36f6fc851e1c8c8a0a907b6ed/href">https://medium.com/media/ce9d7fa36f6fc851e1c8c8a0a907b6ed/href</a></iframe><p>You can see in the first loadPhoto.swift file that we are using a completion handler. It returns not on the main thread and then we call dispatch main async to get back on the main thread and set the image. We have to worry about threading and locking resources. Note: The completion handler could have switched to main thread before calling but I think that is not a good design approach. Now, enter the <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency#Task-Cancellation">unstructured concurrency</a>. We simply wrap the await in a task and the rest is done for you. You can mark shared resouces with <em>actor.</em> It doesn’t look much different nested in a do catch but to me it looks so much more elegant and straight forward.</p><p>I won’t touch on main actor too much, but, it is a nice way to coordinate resources that are immediately thread safe.</p><p>I think that this is great leap for Swift and I am late to the party because it has been around for a couple of years. But, it didn’t seem well thought out when async/await first arrived. You have to laugh at the fact that async await seems borrowed from java script. It makes me wonder who is driving the Swift evolution. That said, both python and typescript seem to follow swift style syntax. Anyway, the ramblings of an engineer. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76431c23baad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Sheet show/dismiss with onResponse controlled by a feature flag]]></title>
            <link>https://tomzurkan.medium.com/swiftui-sheet-dismiss-with-onresponse-22bc6d10e873?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/22bc6d10e873</guid>
            <category><![CDATA[experimentation]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 00:20:21 GMT</pubDate>
            <atom:updated>2023-02-16T20:21:32.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you want to display a coupon with a modal dialog that has a button to redeem. In a feature addition like this, you may want to put it behind a feature flag. A feature flag is a way of wrapping a feature so that it can be remotely turned on or off (like show the coupon or not). You can also use feature flags to pass values like string, json, etc. For now, we are only looking at basic on/off feature flag.</p><p>So, what I wanted to do was show or hide the sheet by toggling the feature flag. I thought I would run through how you would use a sheet and a feature flag if it were critical that the sheet responded instantly to any changes in feature flag status. You could have easily used a timer or some other programmatic mechanism to trigger the display or dismissal of a sheet. I thought a feature flag would be a good way to demonstrate.</p><p>I am going to sudo code the feature flag because the feature flag client you use is irrelevant in this conversation. You can grow your own, or use something like LaunchDarkly, Split, or even Optimizely.</p><p>First, you are going to initialize your feature flag client and broadcast any changes.</p><pre>import SwiftUI<br><br><br>class GlobalListener : FeatureFlagChangeListener {<br>    static let NOTIFICATION_NAME = &quot;FeatureFlagUpdated&quot;<br>       <br>    func feautureFlagChange(ffKey:String) {<br>        DispatchQueue.main.async {<br>            NotificationCenter.default.post(name: Notification.Name(GlobalListener.NOTIFICATION_NAME), object: ffKey)<br>        }<br>    }    <br>}<br><br>let globalListener = GlobalListener()<br><br>@main<br>struct MyFeatureFlagAppApp: App {<br>    <br>    init() {<br>        OptimizelyClient.initialize(sdkKey: &quot;someKey&quot;, listener: globalListener) { err in<br>            if let err = err {<br>                logger.error(err.localizedDescription)<br>            }<br>            else {<br>                NotificationCenter.default.post(name: Notification.Name(GlobalListener.NOTIFICATION_NAME), object: nil)<br>            }<br>        }<br>    }<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}</pre><p>Ok, so above, we setup our listener and initialized our feature flag client. When we detect a feature flag change, we send out a Notification Center notification. Keep in mind that this technique could be used with other programatic mechanisms such as a timer or something else.</p><p>Finally, we have the content view, observable content, and the detail coupon view listed below.</p><pre>import SwiftUI<br><br>struct CouponView: View {<br>    var message: String<br>    @Binding var isPresented: Bool<br>    <br>    var body: some View {<br>        VStack {<br>            Text(message)<br>            Button(&quot;Redeem Coupon&quot;) {<br>                isPresented = false<br>                // let them get the discount<br>            }<br>        }<br>    }<br>}<br><br>class ObservableContent : ObservableObject {<br>    @Published var showingCoupon = false<br><br>    static let defaultInstance = ObservableContent()<br>}<br><br>struct ContentView: View {<br>    @StateObject private var coupon = ObservableContent.defaultInstance<br><br>    var id:NSObjectProtocol?<br>    <br>    init() {<br>        id =  NotificationCenter.default.addObserver(forName: NSNotification.Name(GlobalListener.NOTIFICATION_NAME), object: nil, queue: nil) { notify in<br>            var str = notify.object as? String ?? &quot;keyIExpect&quot;<br>            if str == &quot;keyIExpect&quot; {<br>            OptimizelyFeatureFlagClient.evaluateBooleanVariation(featureFlagKey: str, defaultValue: false, completionHandler: { enabled in<br>                 DispatchQueue.main.async {<br>                     ObservableContent.defaultInstance.showingCoupon = enabled<br>                 }<br>            })<br>        }<br>    }<br>    <br>    var body: some View {<br>        VStack {<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundColor(.accentColor)<br>            Text(&quot;Hello, world!&quot;)<br>            <br>        }<br>        .padding()<br>        .sheet(isPresented: $coupon.showingCoupon) {<br>            CouponView(message: &quot;Coupon for 100% off&quot;, isPresented: $coupon.showingCoupon).onReceive(NotificationCenter.default.publisher(for: Notification.Name(rawValue: GlobalListener.NOTIFICATION_NAME))) { notify in<br>              var str = notify.object as? String ?? &quot;keyIExpect&quot;<br>              if str == &quot;keyIExpect&quot; {<br>                OptimizelyFeatureFlagClient.evaluateBooleanVariation(featureFlagKey: str, defaultValue: false, completionHandler: { enabled in<br>                   DispatchQueue.main.async {<br>                     ObservableContent.defaultInstance.showingCoupon = enabled<br>                   }<br>                })            <br>              }<br>           }<br>        }<br>    }<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p>So, what is going on with the code above? First, you have an observable object in your content view as a state object. You then use binding to bind that published item with the coupon view’s isPresented. Then the sheet ends up with isPresented equal to true when the feature flag is on. The coupon detail view uses the views <a href="https://developer.apple.com/documentation/swiftui/view/onreceive(_:perform:)">onReceive</a>. We use the notification center default publisher with the notification name. If the flag turns false, the showingCoupon is also false causing CouponView to also set isPresented to false which dismisses the detail view or coupon.</p><p>Lastly, you launch your app and turn on your feature flag:</p><p><a href="https://youtube.com/shorts/KuL6Y94i_nk">Simulator Screen Recording iPhone 14 Pro 2023 02 16 at 12 11 30</a></p><p>Oh no! It says 100% off on the coupon. Go over and switch off the feature flag and the coupon disappears. Phew!. This is just an over dramatization of why feature flags are important while also showing how to control a sheet that is displayed without user interaction.</p><p>I hope this short article helps you in your SwiftUI coding. I think SwiftUI is amazing fun and a massive improvement over UIViewControllers and Xibs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22bc6d10e873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A datastore for iOS that uses file or the keychain]]></title>
            <link>https://tomzurkan.medium.com/a-datastore-for-ios-that-uses-file-and-the-keychain-bc1c0faf9c4a?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc1c0faf9c4a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[keychain]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 01:59:15 GMT</pubDate>
            <atom:updated>2022-08-12T22:45:37.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOhMKHuAB5BmU4KgPWAaZQ.png" /></figure><p>There is almost always a need for some sort of data store or persistent storage implementation for your app or SDK. We have a lot of options when it comes to storing data on our iOS device (UserDefaults, SQLite, File, Core Data, Keychain, etc.). In this article we are going to discuss file based persistent storage and the keychain.</p><p>First, let’s create our protocol for the DataStore:</p><pre><strong>protocol</strong> DataStore {<br>  <strong>associatedtype</strong> T : Codable<br>  <strong>func</strong> getItem(forKey: String) -&gt; T?<br>  <strong>func</strong> removeItem(forKey: String)<br>  <strong>func</strong> putItem(forKey: String, item: T)<br>}</pre><p>The above is a simple datastore that supports codeable data types. It has a simple getItem, removeItem, and putItem. There is only one item type per datastore.</p><p>I found that in order to include the datastore into another class, I needed to create a default generic implementation in order to define the type alias and include that as the super class that any other generics implementing would derive from:</p><pre><strong>import</strong> Foundation</pre><pre><strong>class</strong> DataStoreImpl&lt;Item : Codable&gt; : DataStore {<br>  <strong>typealias</strong> T = Item<br>  <strong>func</strong> getItem(forKey: String) -&gt; T? {<br>    <strong>return</strong> <strong>nil<br>  </strong>}<br>  <strong>func</strong> removeItem(forKey: String) {}<br>  <strong>func</strong> addItem(forKey: String, item: T) {}<br>}</pre><p>This generic implementation class allowed me to create other generics classes from it for different implementations that can be included in another class. So, in the following:</p><pre><strong>class</strong> SomeOtherClass {<br>  storage:DataStore<br>}</pre><p>The above would not compile because it does not know the type alias. Instead, we need to define it like the following:</p><pre><strong>class</strong> SomeOtherClass&lt;Item:Codable&gt; {<br>  storage:DataStoreImpl&lt;Item&gt;<br>}</pre><p>Now, I have some other class like a queue that could define an item to hold and the list to hold them in like the following:</p><pre><strong>class</strong> DataQueueImpl&lt;Item: Codable&gt; : DataQueue {<br>  <strong>let</strong> dataStore:DataStoreImpl&lt;[Item]&gt;<br>  <strong>let</strong> name:String<br>  <strong>let</strong> lock:DispatchQueue<br>  <strong>let</strong> queueSize: Int<br>  // pass in datastore to use at initialization<br>  <strong>typealias</strong> T = Item<br>}</pre><p>From there, I can write a simple file datastore as an example implementation:</p><pre><strong>import</strong> Foundation</pre><pre><strong>class</strong> DataStoreFile&lt;Item: Codable&gt; : DataStoreImpl&lt;Item&gt; {<br>  <strong>var</strong> lock: DispatchQueue<br>  <strong>var</strong> url:URL<br>  <strong>init</strong>(name:String) {<br>    lock = DispatchQueue(label: name, qos: .default)<br>    #if os(tvOS) || os(macOS)<br>       <strong>let</strong> directory = FileManager.SearchPathDirectory.cachesDirectory<br>    #else<br>       <strong>let</strong> directory = FileManager.SearchPathDirectory.documentDirectory<br>    #endif<br>    <strong>if</strong> <strong>let</strong> url = FileManager.default.urls(for: directory, in:     .userDomainMask).first {<br>      <strong>self</strong>.url = url.appendingPathComponent(name, isDirectory: <strong>false</strong>)<br>    } <strong>else</strong> {<br>      <strong>self</strong>.url = URL(fileURLWithPath: name)<br>    }<br>  }<br>  <strong>override</strong> <strong>func</strong> getItem(forKey: String) -&gt; Item? {<br>    <strong>var</strong> item:Item?<br>    lock.sync {<br>      <strong>guard</strong> <strong>let</strong> data = <strong>try</strong>? Data(contentsOf: <strong>self</strong>.url) <strong>else</strong> {<br>        <strong>return<br>      </strong>}<br>      <strong>let</strong> dict = <strong>try</strong>? JSONDecoder().decode(Dictionary&lt;String,Item&gt;.<strong>self</strong>, from: data)<br>      item = dict?[forKey]<br>    }<br>    <strong>return</strong> item<br>  }<br>  <strong>override</strong> <strong>func</strong> removeItem(forKey: String) {<br>    lock.async {<br>      <strong>guard</strong> <strong>let</strong> data = <strong>try</strong>? Data(contentsOf: <strong>self</strong>.url) <strong>else</strong> {<br>        <strong>return<br>      </strong>}<br>      <strong>var</strong> dict = <strong>try</strong>? JSONDecoder().decode(Dictionary&lt;String,Item&gt;.<strong>self</strong>, from: data)<br>      dict?.removeValue(forKey: forKey)<br>      <strong>if</strong> dict != <strong>nil</strong>, <strong>let</strong> d = <strong>try</strong>? JSONEncoder().encode(dict!) {<br>        <strong>try</strong>? <strong>self</strong>.write(data: d)<br>      }<br>    }<br>  }<br>  <strong>private</strong> <strong>func</strong> write(data d:Data) <strong>throws</strong> {<br>    <strong>try</strong> d.write(to: <strong>self</strong>.url, options: [.atomic, .completeFileProtection])<br>  }<br>  <strong>override</strong> <strong>func</strong> putItem(forKey: String, item: Item) {<br>    lock.async {<br>      <strong>guard</strong> <strong>let</strong> data = <strong>try</strong>? Data(contentsOf: <strong>self</strong>.url) <strong>else</strong> {<br>        <strong>let</strong> d = [forKey: [item]]<br>        <strong>if</strong> <strong>let</strong> data = <strong>try</strong>? JSONEncoder().encode(d) {<br>          <strong>try</strong>? <strong>self</strong>.write(data: data)<br>        }<br>        <strong>return<br>      </strong>}<br>      <strong>var</strong> dict = <strong>try</strong>? JSONDecoder().decode(Dictionary&lt;String,Item&gt;.<strong>self</strong>, from: data)<br>      <strong>if</strong> dict == <strong>nil</strong> {<br>        dict = [forKey: item]<br>      }<br>      dict?[forKey] = item<br>      <strong>if</strong> dict != <strong>nil</strong>, <strong>let</strong> d = <strong>try</strong>? JSONEncoder().encode(dict!) {<br>        <strong>try</strong>? <strong>self</strong>.write(data: d)<br>      }<br>    }<br>  }<br>  <strong>typealias</strong> T = Item<br>}</pre><p>In the above implementation, we use a dictionary to hold any number of items by name although they must be the same type. The item must support codable so we can convert it to JSON data. The dictionary is backed by a file. The item held could be a list of items such as described above in the queue or a single item.</p><p>Finally, I wanted to discuss using the iOS keychain. The file store above uses completeFileProtection. That means that the file is encrypted and should only be readable by the application. But, sometimes, you might want something a little more secure than that. Now, we have the keychain. The keychain is a system wide keychain where you can store encrypted items. Below is an implementation of the keychain datastore:</p><pre><strong>import</strong> Foundation<br><strong>import</strong> Security<br><strong>class</strong> DataStoreKeyStore&lt;Item: Codable&gt; : DataStoreImpl&lt;Item&gt; {<br>  <strong>let</strong> service : String<br>  <strong>var</strong> keychainHolders = [String: KeychainPasswordItem]()<br>  <strong>init</strong>(key:String) {<br>    service = key<br>    <strong>do</strong> {<br>      <strong>let</strong> khs = <strong>try</strong> KeychainPasswordItem.passwordItems(forService: service)<br>      <strong>for</strong> k <strong>in</strong> khs {<br>        keychainHolders[k.account] = k<br>      }<br>    }<br>    <strong>catch</strong>(<strong>let</strong> e) {<br>      print(e)<br>    }  <br>  }<br>  <strong>override</strong> <strong>func</strong> getItem(forKey: String) -&gt; Item? {<br>    <strong>if</strong> <strong>let</strong> kh = keychainHolders[forKey] {<br>      <strong>if</strong> <strong>let</strong> key = <strong>try</strong>? kh.readPassword() {<br>        <strong>return</strong> <strong>try</strong>? JSONDecoder().decode(Item.<strong>self</strong>, from: key)<br>      }<br>    }<br>    <strong>return</strong> <strong>nil<br>  </strong>}<br>  <strong>override</strong> <strong>func</strong> removeItem(forKey: String) {<br>    <strong>if</strong> <strong>let</strong> kh = keychainHolders[forKey] {<br>      <strong>do</strong>{<br>        <strong>try</strong> kh.deleteItem()<br>        keychainHolders.removeValue(forKey: forKey)<br>      }<br>      <strong>catch</strong> {<br>        print(error)<br>      }<br>    }<br>  }<br>  <strong>override</strong> <strong>func</strong> putItem(forKey: String, item: Item) {<br>    <strong>let</strong> kh = KeychainPasswordItem(service: service, account: forKey, accessGroup: <strong>nil</strong>)<br>    removeItem(forKey: forKey)<br>    <strong>do</strong> {<br>      <strong>let</strong> data = <strong>try</strong> JSONEncoder().encode(item)<br>      <strong>try</strong> kh.savePassword(data)<br>      keychainHolders[forKey] = kh<br>    }<br>    <strong>catch</strong> {<br>      print(error)<br>    }<br>  }<br>  <strong>typealias</strong> T = Item<br>}</pre><p>The above uses the keychain to store the item as a password string because it is an encoded Data object. The KeyChainPasswordItem is based on the <a href="https://developer.apple.com/library/archive/samplecode/GenericKeychain/Listings/GenericKeychain_KeychainPasswordItem_swift.html#//apple_ref/doc/uid/DTS40007797-GenericKeychain_KeychainPasswordItem_swift-DontLinkElementID_7">example</a> from apple for generic keychain storage. But I adapted it so as not to go string to data. It uses the key chain to add the object as a password byte array to the keychain.</p><p>Again, I wrote this article because it was hard to find how to save a generic item to the keychain. As you can see it is pretty straightforward. The file with complete protection might be enough for most uses. But, if you want to provide some extra level of security, then the keychain is a good alternative. Keep in mind that you really don’t want to store any sensitive data on the device. But, any data could be considered sensitive. With that said, even storing simple items might be better served to be encrypted.</p><p>I hope this article, which is pretty thick in code, helps developers to better understand how to implement a data store using either file or keychain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc1c0faf9c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Logback with Android to Extend or Enhance your Logging]]></title>
            <link>https://tomzurkan.medium.com/using-logback-with-android-to-extend-or-enhance-your-logging-6217bfd486dc?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/6217bfd486dc</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Fri, 13 May 2022 00:36:49 GMT</pubDate>
            <atom:updated>2022-05-13T16:03:39.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*8qgiQExsCDpAISbQy_F_gQ.jpeg" /><figcaption>Android and Logback play well together</figcaption></figure><p>Using Logback with Android to Extend or Enhance your Logging</p><p>If you are using any jars or sdks in your app, then you are more than likely familiar with <a href="https://www.slf4j.org/">slf4j</a>. Slf4J is an abstraction layer for your logging implementation. So, most SDKs would choose slf4j-api and allow the application to do the implementation using something like <a href="https://logging.apache.org/log4j/2.x/">log4j</a> or <a href="https://logback.qos.ch/index.html">logback</a>.</p><p>Today, we are going to talk about logback briefly as a way to proxy your logging by using <a href="https://logback.qos.ch/manual/appenders.html#whatIsAnAppender">appenders</a>. Why would you want to do that? You can use the appender to send specific errors to your splunk log or some other service. Or, you could filter out specific log messages.</p><p>Implementing appenders is pretty straightforward. The logback implementation uses appenders to do the actual logging. And, you can add appenders. You provide a <a href="https://logback.qos.ch/manual/configuration.html">configuration</a> file, usually logback.xml and that is picked up with your logback initialization and used.</p><p>There are two ways you can implement your logback.xml. Sometimes, there is already a logback.xml file already in your classpath. In that case, you would not name your logback file logback.xml but something unique (i.e. mylogback.xml). Below we will discuss implementing first straight logback.xml and then how to load your own logback config programmatically.</p><p>In Android, all you need to do is create a new Android Resource Directory “src/main/resource” and add logback.xml under that resource. Logback will automatically pick up that “file” (I say file in quotes because apparently apk does not actually have files per say). Below are some illustrations to show the setup and usage of logback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*G91hBJOZw6be1vmo" /></figure><p>Below is an example logback.xml file:</p><pre>&lt;configuration&gt;<br>    &lt;appender name=&quot;MYAPPENDER&quot; class=&quot;com.mypackage.demoapp.MyAppender&quot;/&gt;<br>    &lt;root level=&quot;info&quot;&gt;<br>        &lt;appender-ref ref=&quot;MYAPPENDER&quot;/&gt;<br>    &lt;/root&gt;<br>    &lt;logger name=&quot;com.package.i.want.to.override&quot; additivity=&quot;false&quot;&gt;<br>        &lt;appender-ref ref=&quot;MYAPPENDER&quot; /&gt;<br>    &lt;/logger&gt;<br>&lt;/configuration&gt;</pre><p>MyAppender is in my package. The logger “override” is for whatever package I want to take log messages from. The <em>additivity</em> keyword is whether it should be added to the appenders list or be the only appender (for instance, should it go on to console). In the case above, I am saying I want messages from com.package.i.want.to.override and then I use my appender. Below is the appender code:</p><pre>package com.mypackage.demoapp<br><br>import android.content.Context<br>import android.util.Log<br>import ch.qos.logback.classic.spi.ILoggingEvent<br>import ch.qos.logback.core.AppenderBase<br>import ch.qos.logback.classic.Logger;<br>import ch.qos.logback.classic.LoggerContext<br>import ch.qos.logback.classic.joran.JoranConfigurator<br>import ch.qos.logback.core.joran.spi.JoranException<br>import ch.qos.logback.core.util.StatusPrinter<br>import org.slf4j.LoggerFactory;<br>import java.io.File<br>import java.io.IOException</pre><pre>class MyAppender : AppenderBase&lt;ILoggingEvent&gt;() {<br>    var appContext: Context? = null<br>    override fun append(eventObject: ILoggingEvent?) {<br>        eventObject?.<em>let </em><strong>{<br>             </strong>Log.i(&quot;i&quot;,&quot;\uD83D\uDC36\uD83D\uDC2E &quot; + <strong>it</strong>.<em>formattedMessage</em>)<br>        <strong>}<br>    </strong>}<br>}</pre><p>Never-mind all those imports. We will talk more about them shortly. For now, you can see that I have created an appender for all info log messages. The logger just logs it to the console via android logging with a dog and cow. Something like this:</p><p><strong>I/i: 🐶🐮 event=CLIENT_INITIALIZATION, message=SOME_PROPERTIES, WERE SET</strong></p><p>That’s it and it is pretty amazing how easy and slick it is to set up. But, sometimes there is another logback.xml file in your classpath that you cannot access and is picked up during build time. What do you do then? Better yet, what if your service relies on the application context so your appender needs the context in order to complete the splunk call possibly through an intent?</p><p>First, instead of putting the file in the resources directory, you can move it to the assets directory and call it mylogback.xml. If you don’t have an Android Assets Directory, create one. As I mentioned above, you cannot access a file directly within your apk. So, you need to read an asset and then write it out to a temporary file. That is why this part is so tricky in Android.</p><p>Your logback file should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*83jP7WBpiMbuQoCP" /></figure><p>Now, your appender needs to be loaded. Below is my example of the appender with functions to handle loading as well:</p><pre>package com.mypackage.demoapp<br><br>import android.content.Context<br>import android.util.Log<br>import ch.qos.logback.classic.spi.ILoggingEvent<br>import ch.qos.logback.core.AppenderBase<br>import ch.qos.logback.classic.Logger;<br>import ch.qos.logback.classic.LoggerContext<br>import ch.qos.logback.classic.joran.JoranConfigurator<br>import ch.qos.logback.core.joran.spi.JoranException<br>import ch.qos.logback.core.util.StatusPrinter<br>import org.slf4j.LoggerFactory;<br>import java.io.File<br>import java.io.IOException<br><br>class MyAppender : AppenderBase&lt;ILoggingEvent&gt;() {<br>    var appContext: Context? = null<br>    override fun append(eventObject: ILoggingEvent?) {<br>        eventObject?.<em>let </em><strong>{            </strong><br>            SplunkLogger.instance.log(appContext, &quot;MyLog&quot;, it.formattedMessage)<br>        <strong>}<br>    </strong>}<br><br>    companion object Register {<br>        fun registerAppender(context: Context) {<br><br>            // assume SLF4J is bound to logback in the current environment<br>            val logContext = LoggerFactory.getILoggerFactory() as LoggerContext<br><br>            try {<br>                val configurator = JoranConfigurator()<br>                configurator.setContext(logContext)<br>                // Call context.reset() to clear any previous configuration, e.g. default<br>                // configuration. For multi-step configuration, omit calling context.reset().<br>                logContext.reset()<br><br>                val file = getFileFromAssets(context, &quot;mylogback.xml&quot;)<br>                configurator.doConfigure(file)<br>                <br>                val log = LoggerFactory.getLogger(Logger.<em>ROOT_LOGGER_NAME</em>) as Logger<br>                val app = log.getAppender(&quot;MYAPPENDER&quot;) as MyAppender<br>                app.appContext = context<br>            } catch (je: JoranException) {<br>                // StatusPrinter will handle this<br>                <em>print</em>(je)<br>                StatusPrinter.printInCaseOfErrorsOrWarnings(logContext)<br>            }<br><br>        }<br><br>        @Throws(IOException::class)<br>        fun getFileFromAssets(context: Context, fileName: String): File = File(context.<em>cacheDir</em>, fileName)<br>            .<em>also </em><strong>{<br>                </strong>if (!<strong>it</strong>.exists()) {<br>                    <strong>it</strong>.<em>outputStream</em>().<em>use </em><strong>{ </strong>cache <strong>-&gt;<br>                        </strong>context.<em>assets</em>.open(fileName).<em>use </em><strong>{ </strong>inputStream <strong>-&gt;<br>                            </strong>inputStream.<em>copyTo</em>(cache)<br>                        <strong>}<br>                    }<br>                </strong>}<br>            <strong>}<br>    </strong>}<br>}</pre><p>Let’s walk through what our appender contains now. We have added a static method registerAppender that takes the application context.</p><p>The registerAppender sets the logging context (not application context) for a configurator. Here I clear out the previous context by calling logContext.reset(). If I didn’t call logContext.reset(), my configuration would just be added to the current configuration which might be what you want.</p><p>For a file used for configuration, I simply look if I have a cache file by that name and if not create one with the asset with that name. So, that gives us a file to hand to the configurator to configure.</p><p>Then after configuration, I can get the appender I’ve added and set the application context if I need to (if not, I just registered the appender). The caveat for this approach is that the register should be called before the package the appender is intended for is used.</p><p>I hope that this helps you with using slf4j and logback. I wrote this article because I couldn’t find anything on using logback native on Android. Appenders are a lightweight solution to making sure the log messages that are important to you are findable. It is also a great way to reduce noise of other packages that may be producing too much logging.</p><p>All the best and Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6217bfd486dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Process]]></title>
            <link>https://tomzurkan.medium.com/github-process-b2bc0f4c146c?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2bc0f4c146c</guid>
            <category><![CDATA[development-process]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[trunk-based-development]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 02:53:37 GMT</pubDate>
            <atom:updated>2022-01-13T02:53:37.884Z</atom:updated>
            <content:encoded><![CDATA[<p>GitHub Process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*UWJE3RJnDvEg6e9ZzyIbag.jpeg" /></figure><p>I’m going to step outside of language agnostic features and talk a little about “process” in this article. Most companies have some sort of GitHub policy in place. However, sometimes they are not following guidelines that I believe work best. So, I thought I would list some of the GitHub policies that work for me.</p><p>First, my methods developed from <a href="https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow#:~:text=The%20overall%20flow%20of%20Gitflow,branch%20is%20created%20from%20main&amp;text=When%20a%20feature%20is%20complete%20it%20is%20merged%20into%20the,branch%20is%20created%20from%20main">git flow</a> into trunk based development similar to how the linked article’s opening paragraph states. But, unlike just working off of master, I have a few other suggestions on the process. What seems to work best is the following:</p><ol><li>Unit Tests. It just needs to be mentioned as number one. You want a high coverage rate, let’s say 85% which is low. Nobody will disagree that unit testing is important and should be done early. But, people rarely do. I find that you can tell the maturity of an engineer by how they approach unit testing.</li></ol><ul><li>You want to make sure that unit tests passing is a requirement for a PR to be merged.</li><li>You want to make sure your Unit Tests are relevant and don’t just mock everything.</li><li>Code coverage should be part of every PR. Think of unit testing as you are developing to flush out your design.</li><li>How about e2e testing? Is it done through unit tests? Maybe if you are a small shop. Otherwise, you need to think about how your e2e testing environment is going to run for CI.</li></ul><p>2. Have a README and include code coverage tags and build tags.</p><p>3. Use <a href="https://semver.org/">semantic versioning</a>. Tag your release and use major.minor.patch[-SNAPSHOT|beta|prerelease] (some use vX.X.X).</p><p>4. Start from master and forget about develop (<a href="https://www.atlassian.com/continuous-delivery/continuous-integration/trunk-based-development">trunk-based development</a>).</p><p>5. The idea is to keep the master branch as “always the main source of truth.”</p><p>6. When you have to create new releases:</p><ul><li>Start with a tag (you can always branch from a tag later).</li><li>Have your CI pick up on a release tag and follow the release cycle. This should not be just an easy nod and dismiss. This flow makes it real easy to tag releases and you can be explicit on whether it is a snapshot, a beta or a release.</li><li>Use a CHANGELOG and basically, copy what is there for the release you are releasing. If you can be extra detailed, add the fix/feature along with the link to the PR.</li></ul><p>7. Once you have to create a branch off of a tag for patches:</p><ul><li>Your new branch should be whatever your latest major and minor are followed by X (e.g. 1.1.X). This branch applies to 1.1.0–1.1.9 with the idea that you can always branch from there for the next release if you can no longer use master. But, the point is to always go back to master as the latest release.</li><li>If you can, apply the fix to master first and then cherry-pick to your branch. There may have to be several cherry picks if you have to patch multiple branches and they could be based off of something other than master (such as the original 1.0.X branch).</li><li>Drive your customers to the latest release whenever possible.</li></ul><p>8. ICs (individual contributors) should create a branch off of master or whatever major minor branch they have to apply this to if it can’t be applied to master (always cherry-pick from master if you can).</p><p>9. You should always create a PR and have it reviewed. If you have a team, have them review it. If not, review it like it was written by someone else and sit on it for a day mull it over. Don’t be a jerk or too nit picky but if you can think of anything to add, it is a great time to add it.</p><p>10. The PR should normally be against master but even when applying cherry-picked fixes, they should also be done in a PR for review.</p><p>11. Use slack and/or email hooks for github updates.</p><p>12. Use github issues even if you use something else for bugs, features, or stories. It is a little more in your face and you can alway reference your jira ticket (there I said it).</p><p>13. GitHub pages are great for docs (start docs early).</p><p>Having said all this, I can’t really recommend a CI or code coverage tool for you. I’ve used Travis, Jenkins, and CircleCI for builds. They all have their pluses and minuses. I lean toward one more than the other but I will leave that up to you to decide. It is pretty easy to add a stage for releasing off a tag in whichever integration environment you chose.</p><p>I’ve written all this as a starting point on the discussion of repo process. I think it’s important to be as verbose as possible on these types of processes. I hope that you find this useful. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2bc0f4c146c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode tricks in Swift]]></title>
            <link>https://tomzurkan.medium.com/leetcode-tricks-in-swift-62a488454339?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a488454339</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Fri, 18 Dec 2020 01:42:26 GMT</pubDate>
            <atom:updated>2020-12-18T01:42:26.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxFE47hoS1oL8Wlu-Wo7HQ.jpeg" /></figure><p>It’s time for another article. This time I am going to talk about a really fun puzzle game I’m sure we have all played. Leetcode. Now, I have no affiliation with Leetcode. But, I really love the programmer puzzles that this site provides. It might seem like a time sink, but, I feel like it sharpens your skills a little while also giving you a fun brain teaser. It’s also great preparation for interviewing.</p><p>I chose to use Swift as my Leetcode challenge language because I enjoy the language. I think it is succinct and graceful programmatically. It’s fun using swift but there are a couple of things that can be a little bit of a gotcha. I thought I might cover a couple of things that I quickly adopted. The examples and approach I am mentioning below illustrate my point perfectly.</p><p>Let’s say you are given a string and you are to return all permutations of that string. If you are going to take that string and construct new strings using ranges, advance by indexes or <em>insert(at:)</em>, it is going to get messy pretty fast. If you have to provide all of the extensions you want, it will also seem like too much effort. Lastly, inserting in a string is inefficient.</p><p>Below is how I would tackle something like this. It does increase your memory footprint but it is also tighter and more readable code.</p><p>Example:</p><p>Give all permutations of String</p><p>e.g. “123” returns <strong>[“123”, “132” , “213”, “231”,”312&quot;, “321”]</strong></p><p>So, If you implemented this using a string it would be somewhat cumbersome. Below is an example implementation of backtracking by mapping the string to a string array and then using that along with reduce to get the permutations.</p><pre><strong>class</strong> Solution {</pre><pre><strong>  var</strong> sol = [String]()</pre><pre><strong>  func</strong> permutations(s:String) -&gt; [String]</pre><pre><strong>    let</strong> ss = s.map({String($0)})</pre><pre>    getPerms(ss, 0)</pre><pre><strong>    return</strong> sol</pre><pre>  }</pre><pre><strong>  private</strong> <strong>func</strong> getPerms(<strong>_</strong> s:[String],<strong>_</strong> index:Int) {</pre><pre><strong>    if</strong> index == s.count {</pre><pre>      sol.append(s.reduce(“”, +))</pre><pre><strong>      return</strong></pre><pre>    }</pre><pre><strong>    var</strong> i = index</pre><pre><strong>    while</strong> i &lt; s.count {</pre><pre><strong>      var</strong> st = s</pre><pre>      st.swapAt(index, i)</pre><pre>      getPerms(st, index + 1)</pre><pre>      st.swapAt(index, i)</pre><pre>      i = i + 1</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p>Above, we use backtracking which might not be the most efficient approach O(n*n!). But, you can see how easy it is to manipulate the string array and then turn that back into a string.</p><p>I keep using these tricks again and again in Leetcode. One thing you might notice here is that I use the while loop and then increment i instead of a for loop. That seems to be the best approach more times than not as well. Here’s another quick example:</p><pre><strong>class</strong> Solution {</pre><pre><strong>  func</strong> reverseWords(_ s: String) -&gt; String {<br>    <strong>let</strong> ss = s.map({String($0)})<br>    <strong>var</strong> words = [String]()<br>    <strong>var</strong> word = [String]()</pre><pre><strong>    var</strong> i = 0</pre><pre><strong>    while</strong> i &lt; ss.count {<br>       <strong>if</strong> ss[i] == “ “ {<br>         <strong>if</strong> word.count &gt; 0 {<br>           words.append(word.reduce(“”, +))<br>           word.removeAll()<br>         }</pre><pre>       }<br>       <strong>else</strong> {<br>         word.append(ss[i])</pre><pre>       }</pre><pre>       i = i + 1</pre><pre>    }</pre><pre><strong>    if</strong> word.count &gt; 0 {</pre><pre>      words.append(word.reduce(“”, +))</pre><pre>      word.removeAll()</pre><pre>    }</pre><pre>    words.reverse()</pre><pre><strong>    return</strong> words.joined(separator:” “)</pre><pre>  }</pre><pre>}</pre><p>Lastly, I will also use a <em>if != nil</em> and then <em>!</em> inside the if statement instead of binding to a new variable. It just seems more efficient in Leetcode. If it was shipping code I would bind. Some people might disagree with these “short cuts” for Leetcode. But, since I’ve done about 50 medium difficulty problems over the last few weeks, it has proven to be the most efficient way in Swift (time footprint usually blows away others. Memory, better than some…).</p><p>So, now I’ve told you a few of my tricks when using swift in Leetcode. If you haven’t had a chance to play around there, do yourself a favor and play around. For me it is my Sunday crosswords type thing. I hope that this helps others. However, I may now go down in my ranking since I let the cat out the bag. :D Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a488454339" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IntelliJ plugin development with Optimizely’s plugin]]></title>
            <link>https://tomzurkan.medium.com/intellij-plugin-development-with-optimizelys-plugin-fea01ee5cde?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea01ee5cde</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[plugins]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 18:17:33 GMT</pubDate>
            <atom:updated>2020-06-15T18:17:33.276Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turn On, Plug in, drop App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/0*rLJGLQ7uOVINHUUV" /></figure><p>That was the name of my hack project at Optimizely. It was an IntelliJ plugin for all versions of IntelliJ with code complete for Go, Java, Kotlin, and Python. The plugin has now been released <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">publicly</a>. It was a great experience. I liked the IntelliJ ecosystem. You can literally create an IDE for a language that doesn’t exist. It essentially does all your basic lexical tokenizing for you.</p><p>After my experience, I wanted to write about it. I am very excited about <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">Optimizely’s</a> plugin and I think it will make using Optimizely seamless. In the <a href="https://medium.com/engineers-optimizely/using-optimizely-plugins-and-extensions-for-feature-development-e45714b38268?source=friends_link&amp;sk=7abc3a17151399aa01f8142c86a97bfb">first article of this series I wrote about how to use the Optimizely plugin</a>. In this second article, I want to talk a little bit about the internals and developing IntelliJ plugins.</p><p>The first thing I’m going to say is that this article is light. You have access to the <a href="https://github.com/optimizely/intellij-plugin">source code</a> and that should speak volumes. Second, when I started this project, I didn’t see too many articles on IntelliJ plugin development. Now, there seems to be tons. So, I don’t want to repeat what other people already wrote. However, I did think that some documentation was hard to find, so I pointed out where you can find those.</p><p>Let’s look at creating a plugin from the perspective of the Optimizely plugin. The plugin is written in Java but could have been written in Kotlin. I like using gradle. It is more adaptable than using the IntelliJ IDE to manage your project. So, take an existing project from the IntelliJ <a href="https://github.com/JetBrains/intellij-sdk-docs/tree/master/code_samples">samples</a> and clone it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*lBh_K9IG8Bos3juK" /></figure><p>Heck, clone the whole repo. It has tons of good <a href="https://github.com/JetBrains/intellij-sdk-docs/tree/master/code_samples">examples</a>. They are buried in the How To Guide so I wanted to link directly to them here. Better yet, clone the <a href="https://github.com/optimizely/intellij-plugin">Optimizely Plugin</a>. It has tons of nice examples as well. I found most of the coding and setup pretty intuitive once I got going. The <a href="https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started.html">How to Guide</a> from Jetbrains was also helpful.</p><p>The other thing that is completely invaluable for auto complete is the PSI Viewer. The PSI stands for <a href="https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi.html">Program Structure Interface</a> which as the name implies gives you the structure of your whole program from file to file. The PSI viewer is available when you debug your plugin by running <em>./gradlew runIde</em>. You will end up poking around the viewer for a while in order to find the right element that you want to auto-complete on.</p><p>PSIViewer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5gr7rO2oSFztJrZ5" /></figure><p>So, let’s go through the Optimizely plugin a little deeper. First, I created <a href="https://github.com/optimizely/intellij-plugin/tree/master/src/main/java/com/optimizely/intellij/plugin/action">actions</a>. The actions are your menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOrbNVP8wjLWN9qJ" /></figure><p>It was easy to <a href="https://github.com/optimizely/intellij-plugin/blob/d2024efe3b1e949c0c34cdb8a867de6e796b7822/src/main/resources/META-INF/plugin.xml#L108">set those up </a>along with an <a href="https://github.com/optimizely/intellij-plugin/blob/d2024efe3b1e949c0c34cdb8a867de6e796b7822/src/main/resources/META-INF/plugin.xml#L161">application level service</a> that the actions used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k74DM7KnoLSIqzIA" /></figure><p>And figure out how to insert text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpMCApGv5o_-AXLl" /></figure><p>You can see that I just use an <a href="https://github.com/optimizely/intellij-plugin/blob/d2024efe3b1e949c0c34cdb8a867de6e796b7822/src/main/java/com/optimizely/intellij/plugin/action/ListAction.java#L173">insert at the caret in the editor</a> and that works out fine. Another thing to notice is that I use a <a href="https://github.com/optimizely/intellij-plugin/blob/master/src/main/java/com/optimizely/intellij/plugin/action/DynamicActionGroup.java">dynamic menu group</a> for “Jump To”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3hGvxXq7khICCNwZ" /></figure><p>The dynamic menu is only available if you have set your SDK key with <strong>option-o s.</strong></p><p>Keyboard shortcuts are important here. They allow you to continue to develop without having to reach for the mouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fTNh1VtqjLVWVZKp" /></figure><p>The key bindings allow the user to use keyboard shortcuts to invoke these menu items. They are defined in the plugin.xml. You can see an example in the action mentioned above.</p><p>Speaking of plugin.xml, you will also notice that I used <a href="https://github.com/optimizely/intellij-plugin/blob/d2024efe3b1e949c0c34cdb8a867de6e796b7822/src/main/resources/META-INF/plugin.xml#L34">optional dependencies</a> to include the auto-complete for each language depending on what was available per IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1kRzyVD7m7QoGJh" /></figure><p>The gradle build became a challenge as I wanted to use one plugin for all the IDEs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bZfDaDSy3_nxz0Pa" /></figure><p>As you can see, I had to settle on a 2019 build. As a matter of fact, the latest version of Android is still built on a 2019 version. If you decide to create a plugin, you will get pretty familiar with the IDE builds and matching the appropriate language plugin build. I hope this saves you some time.</p><p>I used <a href="https://en.wikipedia.org/wiki/Swing_(Java)">Java Swing</a> for the debug dialog and that is the UI for all IntelliJ based IDEs. The dialog wrapper for the debug dialog was a lot of fun. I didn’t know <a href="https://en.wikipedia.org/wiki/Swing_(Java)">Java Swing</a> very well before this. I thought it was pretty easy to pick up and organize. It kind of had a ReactJS feel to it. It was easy enough to create a menu action that invokes the dialog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXMYh2mJBHxaR2VY" /></figure><p>Notice how the views take models and how the lambdas allow access to other ui elements. It’s pretty nice. The BoxLayout seemed to work best.</p><p>For the auto complete which is language specific, the PSI Viewer again was invaluable. There was a lot of trial and error in finding the right element to listen for in the CompletionContributor. I finally ended up creating a gradle based debug configuration to debug from the IDE. That was also very useful. Simply create a gradle run environment with intellij-plugin as the project and runIde as the task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IvfhIbtcYGA95XfS" /></figure><p>That concludes our high level walkthrough of the IntelliJ plugin. I hope it gives you confidence in using it as well as any ideas for developing new plugins.</p><p>Please checkout the open source <a href="https://github.com/optimizely/intellij-plugin">Optimizely plugin</a>. It will definitely help you get started if you want to write your own. I know that most of the work was poking around in all the documentation to find something. For instance, how to insert into the editor. That said, I also think that the plugin itself will be useful for those who develop on any IntelliJ based product. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea01ee5cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Optimizely Plugins and Extensions for Feature Development]]></title>
            <link>https://medium.com/engineers-optimizely/using-optimizely-plugins-and-extensions-for-feature-development-e45714b38268?source=rss-bf76af7c6eae------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45714b38268</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Tom Zurkan]]></dc:creator>
            <pubDate>Wed, 27 May 2020 00:26:45 GMT</pubDate>
            <atom:updated>2020-05-27T17:47:33.438Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer using <a href="https://www.optimizely.com/rollouts/">feature flags</a> while building Optimizely, I had to switch back and forth cutting and pasting between the application and the IDE while developing. This made my development flow hard to maintain because of all the context switching between application and IDE. It is also error prone with no way to test my configuration or audience other than to develop and run the project.</p><p>So, I wrote an <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">IntelliJ plugin for Optimizely</a> and the <a href="https://marketplace.visualstudio.com/items?itemName=optimizely-fullstack.optimizely">vscode extension</a>, which helps you to manage, and use <a href="https://www.optimizely.com/rollouts/">feature flags</a> and experiments within the IDE. I will walk through an example using the IntelliJ plugin which works with all JetBrains IDEs. But, the same applies to the vscode extension with some slight differences.</p><p>If you aren’t familiar with <a href="https://www.optimizely.com/optimization-glossary/feature-flags/">feature gating</a> and <a href="https://www.optimizely.com/optimization-glossary/feature-test/">experimentation</a>, <a href="https://www.optimizely.com/resources/progressive-delivery-experimentation-ebook/">adopting these useful tools</a> will allow you mitigate the risk of launching new features from deploying to delighting customers. If you are already familiar with using Optimizely, great! This will show you how to easily integrate this helpful plugin with your Optimizely workflows.</p><p>The <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">IDE plugin</a>:</p><ul><li>Shows the feature flag or experiment key by auto-complete</li><li>Accesses all of Optimizely config options via keyboard shortcuts</li><li>Insert attribute, event, and variable/variation keys available from the keyboard</li><li>Jumps straight to a feature or experiment edit page and add and consume variables easily</li><li>Shows a debug dialog that allows you to debug your configuration and complex audience combinations</li></ul><p>Let’s go through a scenario on how you might use Optimizely and the <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">IntelliJ PlugIn</a>. The Optimizely IntelliJ plugin supports auto-complete for Go, Java, Kotlin and Python.</p><p>Before using the plugin, you’ll need to install the <a href="https://www.optimizely.com/platform/full-stack/">Optimizely SDK</a> in your application. You can go to the <a href="https://www.optimizely.com/developer-docs/">developer documentation</a>, pick your language and SDK to get started.</p><p>You will also want to install the <a href="https://plugins.jetbrains.com/plugin/13969-optimizely">Optimizely Plugin</a> (extension is mentioned below), which is available by going to Preferences &gt; Plugin. Optimizely plugin will be in your list of <a href="https://plugins.jetbrains.com/marketplace">marketplace</a> plugins that you can install. Simply click on install and install the plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6U9FJwIYhOsKGcez" /></figure><p>Next, we will planout what features we want to gate behind a <a href="http://optimizely.com/rollouts">feature flag</a> and walk through an example of creating a feature flag and implementing it in the IDE. In the example below we are going to create a feature flag for a new coupon popup for our Android project. We can gate this new coupon feature using a feature flag. First, we will create the feature, then create an audience, in this case for New York and California users, and then test it in the debug dialog. After that is all setup, we can add the code to our project.</p><p>After creating the <a href="https://docs.developers.optimizely.com/rollouts/docs">feature flag</a> and an audience (for instance, you want to target by location, which you will pickup in the HTTP Header or via mobile location), we will switch over to the IDE.</p><p>The driving configuration key is the <a href="https://docs.developers.optimizely.com/rollouts/docs/manage-environments">SDK key</a> for the Optimizely environment we are using. Hit option/alt — o and s and then the SDK key entry screen will pop up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hsHwvXKBi4jAWxW1" /></figure><p>From there if you are using Go, Java, Kotlin or Python, you can use autocomplete while typing Optimizely SDK methods like <a href="https://docs.developers.optimizely.com/full-stack/docs/get-feature-variable-java">isFeatureEnabled, getFeatureVariableString, and activate</a>. If you are using a different language or don’t want to use autocomplete, you can use <strong>option-o e</strong> (for experiment) <strong>option-o f </strong>(for feature) <strong>option-o v</strong> lists the last variables or variations depending on which feature or experiment you picked last.</p><p>Here’s an example of ruby which does not have autocomplete yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*O7FUoHzcps-Jbyqo" /></figure><p>And a Java example also using activate with autocomplete:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*s_fjiGOUhgSWTVALRriBcA.gif" /></figure><p>Jumping back to our Java example, we want to see if there is a feature key show_coupon, the name we gave to our coupon feature, and if it is true, then show the coupon. Below is a snapshot of the autocomplete with “show_coupon.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_iMHT2kvXwexbq3a" /></figure><p>First, let’s check if the coupon is enabled. If it is, then use the feature key by passing it to our Android <a href="https://developer.android.com/reference/android/app/Activity">activity</a> to show the coupon. We can pass it as extra data in the intent as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DxMK6YqIzfvGEmtn" /></figure><p>You can also easily access feature variables by type with auto complete. Below is a gif of getting the message. Notice that only feature variables with the appropriate type are shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SteYYrdeNToPUTl2bywZqw.gif" /></figure><p>In the gif, the getFeatureVariableString function will return only variables of type string. It relies on the fact that the first variable is a quoted string of the feature key.</p><p>Great! We also want to be able to react if the feature changes. So, we will add a notification handler and respond by resetting that variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mNdvxYFOZ6lcnBE6" /></figure><p>Ok, now we have a feature wrapped in a feature flag that is updated whenever the feature flag changes. But, how about if we want to add an audience so that we can roll out the feature to certain audiences?</p><p>The next thing we would do is create our<a href="https://docs.developers.optimizely.com/full-stack/docs/define-audiences-and-attributes"> audience in Optimizely</a>.</p><p>So, go to the menu, look under <em>Jump To </em>and jump to the show_coupon edit page.</p><p>Create an audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JbN7vH7x-HuvTIvU" /></figure><p>In this case, we created an audience for NY or CA only. Next, we can use the Optimizely Plugin to test and add our audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H4OzIo00NvXYOYX1" /></figure><p>Ok, so we just did isFeatureEnabled for my show_coupon and we can see that there was an audience and we were not in it. Now, let’s add an attribute and rerun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PU2o4CxMH1d4AIjr" /></figure><p>Ah, now we added a location and if it is CA or NY, we will show the coupon. We can change the audience later to be none or something else if we want to increase or decrease the number of customers exposed to the feature. The debug dialog can be really useful when you have very complex audiences and you want to verify how they will work.</p><p>Now, we add the audience portion so that we can rollout. We might want to take into account different attributes as well, such as age or some other demographic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hq75pn2XX65DFlox" /></figure><p>And maybe add any other demographics we might want such as X or Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L0dgILZgOHWLKGmr" /></figure><p>Finally, we want to make sure that we include these attributes in our feature calls. Right now, isFeatureEnabled is where it is most useful (it is used to determine if you are part of a rollout or not) unless your feature is part of an experiment (in which case you can get non-default values for a feature that is on). But, with the addition of targeted features rollouts, you will be able to get different feature variables values based on whether you are targeted or not. So, let’s make sure and add those attributes to all our calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pnYO3Q9D1QoY3RSa" /></figure><p>So, we have walked through adding a new feature and wrapping it in a feature flag using the Optimizely plugin. The plugin is really useful for initial design and development, however, I would advocate refactoring your code so that your feature flags and conditions are behind a wrapper when you push to production. That way, in the future, you can easily swap out feature names, or deprecate a feature.</p><p>VSCode Extension</p><p>One last thing I would like to mention is that I also wrote a vscode extension available with the same functionality (once you start a quote, it lists all features or experiments). It also filters your feature variable by type for the second argument. Below is an example of vscode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TvTcJPpRfdeZLQ2U" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1QrAs968GqeOfw5B" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*jJBdjL3am0YH761dqqpgtA.gif" /></figure><h3>Conclusion</h3><p>I can’t stress enough how useful <a href="https://www.optimizely.com/rollouts/?utm_campaign=">feature flagging</a> and <a href="https://www.optimizely.com/platform/full-stack/">experimentation</a> can be for product development. They are really invaluable if you want to advance your UI and feature set quickly and confidently.</p><p>I really hope that people find this plugin and/or extension helpful for creating a reliable well tested experiment and feature environment. We will adapt as we get feedback from engineers, please send along any feedback you have! You can give feedback through the <a href="https://plugins.jetbrains.com/plugin/13969-optimizely/reviews">PlugIn review section</a> or open an issue in the <a href="https://github.com/optimizely/intellij-plugin/issues">github repository</a>. The same holds true for the <a href="https://marketplace.visualstudio.com/items?itemName=optimizely-fullstack.optimizely&amp;ssr=false#review-details">vscode extension</a>.</p><p>If you are interested in getting started with progressive delivery, you can sign-up for a free <a href="https://www.optimizely.com/rollouts/?utm_campaign=">Optimizely Rollouts </a>account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45714b38268" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineers-optimizely/using-optimizely-plugins-and-extensions-for-feature-development-e45714b38268">Using Optimizely Plugins and Extensions for Feature Development</a> was originally published in <a href="https://medium.com/engineers-optimizely">Engineers @ Optimizely</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>