Safe Swift array using Dictionary

Ever wanted to get array elements by index in a safe way, i.e. to retrieve nil in case of index out of bounds rather than having the app crashed? You might have reached into solutions that involved collection extensions like this.

(Sure, the idea below only addresses the get operation, but for many use cases, and especially if your array isn’t huge and the performance penalty is small or very small, I think it’s just easier – and more elegant – to do it by creating a simple dictionary out of your array instead.)

Assuming you have a collection named array, map its values to keys defined by zero-based indexes like this:

let safeArray = Dictionary(uniqueKeysWithValues: zip(0..., array))

Then you can safely get elements from the “array” (i.e. dictionary) using random indexes, as you would expect:

let value = safeArray[index] ?? defaultValue;


Posted in Swift | Tagged , , , | Leave a comment

SHA*Managed + FIPS = hate 💔

door green closed lock

Fotografie de Life Of Pix pe

If you write .NET software that cryptographically validates signatures, e.g. you verify a customer’s license at runtime, be aware of issues when the check runs on US government-certified FIPS-enabled computers.

Chances are that you run Sha256Managed algorithm for computing a hash to compare it to that of your customer’s resource. (Or Sha1Managed. Or another *Managed, whatever.)

And it worked well for you. In most cases. Or until a specific customer.

The issue is that these (actually pretty fast) algorithms are not supported on FIPS-enabled Windows machines. Specifically, they will throw runtime exceptions whenever they would be called if this [DWORD] registry key is set to 1 on the target machine (try it yourself):

(See also Microsoft’s 2014 recommendation against enabling FIPS blindly, but this won’t help if your customers are, regardless, still forced into their FIPS-enabled environments.)

To solve the issue, however, you may simply use another algorithm – even that documentation doesn’t clearly state it – use Sha256Cng (or Sha1Cng) instead.

While a bit slower, your check will be performed successfully now. And if in doubt regarding the performance issue, you can also try with the managed algorithm first, and use CNG version just in [exceptional] case; that’s it.

Posted in .NET | Tagged , , , , | Leave a comment

Funny one – but it doesn’t crash

Would you expect this SwiftUI code to crash or otherwise fail to run?

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: ContentView()) {
                Text("Show another")
            }.navigationBarTitle("Recursive navigation")

Nope, body property for the new ContentView is not called until navigation occurs, so it runs as um… expected? 🙂

Screen Shot 2019-10-29 at 13.35.40

Posted in SwiftUI | Tagged , | Leave a comment

Small SwiftUI annoyances

Some (maybe minor) things that I’ve observed while learning SwiftUI and doing some hands on testing:

  • When you present a set of unrelated items in a Picker (i.e. without ForEach) or a set of random tab items in a TabView (in similar conditions) you need to tag() them with integer values if you want selection by index to work. (With ForEach you don’t need to – it seems it does it internally?)
  • When you create a Button you need to pass its action as the first argument of the initializer, and the content as a last closure. But when you create an Alert.Button the Text is expected as the first argument, and the action as a final closure.
  • Corner radius on border modifier is now obsolete. So you are forced to use overlay instead:
    .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray))
    Or, if you need a custom background too, this will become an ugly dinosaur with repeating constant:
    .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray))
    .cornerRadius(10) // cut background too

    Oh my.
  • scaleEffect modifier will resize the view but layout won’t be affected, i.e. it might be displayed on top of (or behind) other views. The behavior is the same as for offset but there the “effect” is somehow expected…
  • A VStack, HStack, etc. can only contain 10 views added manually into SwiftUI code; you need to use Group to allow more (but that’s OK most of the times).

But there are a lot of good things, too, which I won’t mention since they are everywhere in SwiftUI blog posts, recently. Except for one that I really liked to find out it exists: the .constant binding – very good for prototyping.

Posted in SwiftUI | Tagged | Leave a comment

Books do make a difference

book book pages bookcase browse

Fotografie de Pixabay pe

You can start coding with any programming language or on top of any framework either with or without reading tech books on those topics. But depending on the selection, your dev experience might vary so much:

  • Go directly hands on with the technology and it will be very fun, but you’ll soon run into miscellaneous, yet possibly very big problems; you’ll then need to stop and read at least the relevant docs, and you might end up with refactoring everything or restarting from scratch (possibly even more than once!)

I did so in my early years as a programmer. By learning just a few of the Basic keywords I was able to do a lot of things. But of course, without knowing about AND and OR I ended up writing subsequent IFs and other ugly code to fulfill even the minimal requirements. (But I must admit, I was just a kid and hadn’t even seen a programming reference book by then.)

  • Read a Get started guide or follow a tutorial first and while it’s going to be boring now and then or here and there, you’ll eventually use less time refactoring and finish your work sooner, overall; sometimes big issues will still arise anyway, being caused by the fundamental differences between the way you thought things work and the way they actually do, forcing you to find ugly workarounds or refactor your code big time again; if you’re lucky enough, however, or if your application is not too complex itself, you might get away with this approach, though.

I used to follow this path since Pascal, up to Windows Forms and even tried it with WPF. It goes well, as long as the framework isn’t tricky enough to either decrease performance if you’re using it in a wrong way (like I did first with WPF) or if it’s simply not intuitive enough (at least in some of its parts).

  • Read an advanced, detailed book on the topic (after going through Get started reference too) and although this would indeed take some precious start-up time, it will serve you the best on the long term: knowing more about the core of your platform will lead you through complex development tasks without pushing you into unexpected performance issues, and knowing some about all the available APIs that it offers will get you very good overall awareness; you’ll know where and what to search for whenever you need something done, you’ll know what wheels to avoid reinventing, and you’ll know many important things about the approaches and components that you can use or reuse in your project.

After more than 25 years since my first line of code, I highly recommend this way, myself. For macOS and iOS development I followed this route directly (I’m actually still on the road with it), and I am sure it was the best decision I could make for the times ahead. It’s so important to know what to use and when, or at least where and what to search for when you need it! Especially since often the underlying software is just not working the way one intuitively believes it should. (And this is true for all platforms in some of their areas or in certain conditions.)

Moreover, I must note that during the years I’ve found that although I absolutely love coding and that I couldn’t live without computers, reading a good tech book can also bring a lot of joy and happiness too. 🙂

(By the way, I prefer paperback books now, despite Kindle’s advantages: I just feel like and don’t regret it; and apparently, other people are on the same track too.)

Posted in Development | Tagged , | Leave a comment

Waterfallish isn’t [always] foolish!

Your first goal is an MVP – minimum viable product [not Microsoft’s most valuable professional.] You define a few features and envision a few screens. Sure, without going into any details. And you go with scrum from the beginning. You’re agile, yeah, right!?

During the first sprints you come up with a simple architecture, supporting one or two features and one or two types of screens, just enough for you to be able to start the real development.

The next few sprints you’re working on similar features and improve the initial ones. For some time, everything is still fine.

Then a completely different type of screen or some very complex requirement details arise for either existing or for newly discussed features and they are not fully supported by your original software design.

You have now a lot of work already done and changing the design completely would require a lot of (logically acceptable, from the agile perspective) refactoring.

In theory, it’s indeed still fine: you shouldn’t prepare anything until it’s really needed. However, the redesign would now require at least two sprints to finish, and your customer is not going to “buy it.” Or even if they did, won’t cha wish your girlfriend you had known about those important requirements beforehand, to incorporate them into your otherwise brilliant initial design?

But it’s too late at this point, so what are you going to do?

You [are forced to] find shortcuts and workarounds to solve the issues… and keep the client happy and the product still “on track.”

And yes, everything moves on. For another while. Until emergencies appear again. Until (eventually) everything becomes a mess. Be sure it will, either sooner or later.

Sprints are still green maybe, but the software is redder and redder.

Maybe you will finish the MVP before the deadline, but hey, could you still maintain that code for much longer without a full refresh afterwards? (Remember: v1 is not supposed to be the last one!)

Don’t do this. Don’t scrum without a reason. Waterfall instead whenever you feel it’s better! Sometimes details must be decided before you actually start coding anything!

Or everything can be a waste of time.

Posted in Development | Tagged , , , , | Leave a comment

Indexing for IndexOf

Today, a short one. But it gave me some not-so-short trouble recently.

Do you happen to use or inherit Collection or any of its subclasses (e.g. ObservableCollection)? Make sure you don’t call its IndexOf method too much. As indicated on Microsoft docs, that is an O(n) operation, and it is therefore fast only if the collection is small.

A workaround that can highly improve the application’s performance in certain situations may be storing and maintaining the collection index values within the item objects themselves. With certain assumptions, though:

  • the collection rarely changes and it’s OK if it takes slightly larger setup and update time spans;
  • the collection would never need to hold null values;
  • item objects cannot be part of multiple collection instances at the same time;
  • items for which you need to call IndexOf are surely in the collection at the time of asking the question.

Some code is available here, with an extract below:

public class Item
    internal int Index { get; set; } = -1;
    public object Content { get; set; }

public class ItemCollection : ObservableCollection
    public new int IndexOf(Item item)
        return item.Index;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)

        switch (e.Action)
            case NotifyCollectionChangedAction.Add:
                SetManagedItems(e.NewStartingIndex, e.NewItems);
            case NotifyCollectionChangedAction.Remove:
                RemoveManagedItems(e.OldStartingIndex, e.OldItems);
            case NotifyCollectionChangedAction.Reset:
            case NotifyCollectionChangedAction.Move:
            case NotifyCollectionChangedAction.Replace:
                SetManagedItems(0, this);

    private void SetManagedItems(int index, IList items)
        foreach (Item item in items)
            item.Index = index++;
        for (var i = index; i < Count; i++)
            this[i].Index = i;

    private void RemoveManagedItems(int index, IList items)
        var removedCount = items.Count;
        for (var i = index; i < Count; i++)
            this[i].Index -= removedCount;


Posted in .NET | Tagged , , , | Leave a comment

Scrum and the city

The Scrum guides proudly state:

  • Development Teams are cross-functional, with all the skills as a team necessary to create a product Increment;
  • Scrum recognizes no titles for Development Team members, regardless of the work being performed by the person;
  • Scrum recognizes no sub-teams in the Development Team, regardless of domains that need to be addressed like testing, architecture, operations, or business analysis; and,
  • Individual Development Team members may have specialized skills and areas of focus, but accountability belongs to the Development Team as a whole.

Organizations trying to enforce this to a team might not realize, however, that people may simply choose to accept sharing the team blame (e.g. in case of possibly missing a deadline for a release) rather than accepting to do things they are not specialized for (e.g. a person who usually writes code may not sign in to define test cases if she is not used to it, even when the sprint’s timeline would be in red.)

This could easily happen when individuals think that such contribution might eventually jeopardize the overall quality of the deliverables that their team produces.

Some people might say that these members are just “not committed enough” (from the utopian point of view), but in my opinion the former ones would then just be fully blind, similar to the way communists were in the 20th century trying to make anybody work for everybody else; without a proper degree of pragmatism, people would easily miss the fact that productivity only flourishes upon specialization (and liberalism.)

The “nonconformist” developers mentioned above may actually be “too” committed to the product instead – so much that they’d rather screw Scrum entirely than deliver lower quality software to their customers; and I’d argue they have all the rights in the world to do so – what would users want: green sprints or, better, good products?…

Update: As readers mentioned to me there is a side story for this as well: very specialized tier teams or individuals that (just kinda) work together are not good either; backend and UI, for example, should be developed in tandem by a single team (or a single developer), and never provided by separate groups upon formal requests.

This one is an older issue that many organizations still face, but the full stack development trends (together with keeping teams small) are partially or at least conceptually solving this – that’s why in this article I originally insisted on the enforced Scrum toxicity alone – it’s a more recent issue, based on a more actual trend. (Note also that in my opinion Scrum itself, just like many other methodologies, may be good enough for specific projects if the teams consensually auto-select and auto-apply it themselves.)

Posted in Development | Tagged , , , | Leave a comment

Hacking the WPF DataGrid: properly hiding rows for unwanted items

blur computer connection electronics

Fotografie de Field Engineer pe

If you even need to hide some DataGridRow elements displayed in a WPF DataGrid please remember these few things – it took me some time to realize and solve them all:

  • If you plan to just set DataGridRow.Visibility to Collapsed when an item shouldn’t be visible on screen, don’t do it. Not without thinking thoroughly, anyway. DataGrid component itself uses virtualization by default (and you probably don’t want to turn it off – it highly improves performance) and there lies a bug that Microsoft closed as “will not solve” (you need to trust me on this one because the Connect page doesn’t seem to exist anymore!): if you have many hidden rows in the visible viewport (i.e. between currently visible items) the vertical scrollbar’s thumb will not get the correct height (the same if you try to work with row heights) – this itself would be understandable in virtualization context, but in some extreme cases (with thousands of rows hidden among a few other hundreds visible in my case) if the end user scrolled by dragging the scroll thumb top to bottom (and maybe fast and repeatedly), the control would crash the app with a stack overflow exception!
  • A better solution that I’ve identified was to use a CollectionView with a Filter as the binding source for the DataGrid.ItemsSource collection (or simply setting CollectionViewSource.GetDefaultView(items).Filter to an appropriate predicate instance). This way, only the items that are supposed to become visible are “seen” by the DataGrid, and the scrollbar then works correctly from the start. But… there is a caveat with this approach too: if you use .NET 4.0 at least (later i.e. in .NET 4.5+ I saw some improvements arrived) there is no way to dynamically refresh the collection view and its bound UI when the filter’s source properties change. To address this you can only perform a CollectionView.Refresh call which is far from what a high performance app (like yours) can accept.
  • Finally you can resolve everything with a middle-man custom collection, optionally managed by a Converter that you apply to the ItemsSource‘s Binding: this collection would initially be set to a list with all items that respect the visibility filter in your true data source, and would then become updated automatically whenever needed:
    • when an item becomes invisible in the input collection, it is removed from the output collection;
    • when an item becomes visible, it is inserted in the output collection at its correct index (this requires a solution of its own! what I’ve personally chosen to do is to find the output collection index of the nearest visible item already existing above the current one, and insert it below that one – without storing the indexes anywhere; the code is fast enough in the common cases);
    • when a visible item is added in the input collection, it is also added to the output collection at the correct index (as described above);
    • when an item is removed, it is removed from the output collection as well.

I wasn’t able to easily extract the code for this from the project I needed it (there are too many specifics and a too generic solution could have been considered overarchitecturing) so I only have some partial code to show (but, I admit, it’s far from perfect – it can use some performance improvements, it requires a custom ItemObservableCollection that triggers an ItemPropertyChanged event whenever any item inside it changes and a custom Item class with an IsVisible Boolean property, it doesn’t optimally treat Move and Replace collection change actions, and it doesn’t deallocate the internal event handlers if the binding is later not needed):

class VisibilityItemsConverter : IValueConverter
    public static VisibilityItemsConverter Instance = new VisibilityItemsConverter();

    private ItemObservableCollection items;
    private ObservableCollection<object> visibleItems;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        items = value as ItemObservableCollection;
        if (items == null)
            return null;
        visibleItems = new ObservableCollection<object>(items.Where(i => i.IsVisible));
        items.CollectionChanged += Items_CollectionChanged;
        items.ItemPropertyChanged += Items_ItemPropertyChanged;
        return visibleItems;

    private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        switch (e.Action)
            case NotifyCollectionChangedAction.Add:
                if (e.NewItems == null)
                foreach (Item item in e.NewItems)
            case NotifyCollectionChangedAction.Remove:
                if (e.OldItems == null)
                foreach (DataTreeGridItem item in e.OldItems)
            case NotifyCollectionChangedAction.Move:
            case NotifyCollectionChangedAction.Replace:
            case NotifyCollectionChangedAction.Reset:
                if (items == null)
                foreach (var item in items.Where(i => i.IsVisible))

    private void Items_ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        if (e.PropertyName == "IsVisible")
            ManageItem(sender as Item);

    private void ManageItem(Item item)
        if (item == null)
        if (item.IsVisible)
            var i = items.IndexOf(item);
            if (i < 0)
            do { i--; } while (i >= 0 && !items[i].IsVisible);
            var previousVisible = i >= 0 ? items[i] : null;
            i = previousVisible != null ? visibleItems.IndexOf(previousVisible) : -1;
            visibleItems.Insert(i + 1, item);
        else // if (!item.IsVisible)
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotSupportedException();


Posted in WPF | Tagged , , , , , | Leave a comment

Don’t set NSPopupButton’s menu.items!

Since macOS 10.14 (Mojave) you can set the items of the internal NSMenu of a NSPopupButton in a Cocoa app using simple code like this:

menu.items = […]

But if your app also targets macOS 10.13 (High Sierra), don’t do it! It will fail to load views there using a (partially misleading) error message like this if you do so:

Failed to set (contentViewController) user defined inspected property on (NSWindow): -[NSMenu setItemArray:]: unrecognized selector sent to instance

This may make you think that it’s the main window’s NSMenu which is in error, but you probably created that within a storyboard… so it will be difficult to find the actual issue.

It’s unknown to me why Xcode lets us build the app without any warning if we set the menu.items that way, without an if @available check. And if we only test on Mojave, it won’t break! (It will just break in production!)

The workaround (once you know about the issue) is very simple (while unfortunately verbose):

for item in […] { menu.addItem(item) }
Posted in macOS | Tagged , , , , , , , , , | Leave a comment