0

I would like to add an extension to Dictionary<Hashable, RangeReplaceableCollection> which would add some functionality only for RangeReplaceableCollection where RangeReplaceableCollection.Element is Value type

I would like to append value a collection which is a value in the dictionary - basically from here. As it was pointed out in comments there is shorter way to do that. One can append to a dict with default value using dict[key, default: value] although there is a note in Dictionary documentation:

Do not use this subscript to modify dictionary values if the dictionary’s Value type is a class. In that case, the default value and key are not written back to the dictionary after an operation.

So the naive way to implement my extension was something like this:

extension Dictionary 
    where Value: RangeReplaceableCollection 
         where RangeReplaceableCollection.Element is ValueType {

I was wondering if it is possible to achieve something like that (and if yes how?).

I have also thought about something like: protocol ValueRangeReplaceableCollection : RangeReplaceableCollection where RangeReplaceableCollection.Element: Int {} to use later as a restriction on value but I couldn't come up with a way to properly do it.

I would appreciate any thoughts on this.

EDIT: I understand that you can just use the extension from the gist and not care about value/reference types. My question is more about Swift generics.

iur
  • 2,056
  • 2
  • 13
  • 30
  • This might be helpful as a first step: https://stackoverflow.com/questions/34725431/check-for-value-or-reference-type-in-swift – Marc Feb 27 '19 at 14:22
  • Sadly it is not possible to create a type constraint for value types, there is no type that could represent all value types (unlike `AnyObject` for reference types). And you also cannot create negated type constraints, so you cannot just say where `!(RangeReplaceableCollection.Element is AnyObject)`. – Dávid Pásztor Feb 27 '19 at 14:23
  • 1
    The obvious solution is to declare an extension for both value and reference types without using `dict[key, default:]`. – Sulthan Feb 27 '19 at 14:23
  • @Marc I was thinking into that direction, even posted a duplicate question about checking ref/value types, but was proposed to ask a more specific question regarding of what I want to achieve with it. – iur Feb 27 '19 at 14:28
  • The note about subscript refers to the case where the dictionary's `Value` type is a class. Why do you want to check if `Value.Element` is a reference type or a value type? – Martin R Feb 27 '19 at 17:14
  • @MartinR to limit the extension scope to value types so the note doesn't apply. At least that was an initial question from which I started wondering if it is possible in Swift to have hierarchy of where clauses somehow. – iur Feb 27 '19 at 18:28

0 Answers0