Duplicate Int in Array , Dictionary or Set in SWIFT -


reading on sets , arrays find set cannot, or not able store duplicate values ( ints, strings, etc ).

knowing this, if solve finding duplicate int in array , 1 method convert array set, how come don't error once array set?

the methods below return bool value if array contains duplicates.

import uikit  func containsduplicatesdictionary(a: [int]) -> bool {      var adict = [int : int]()      value in {         if let count = adict[value] {             adict[value] = count + 1             return true         } else {             adict[value] = 1         }     }      return false }  containsduplicatesdictionary(a: [1,2,2,4,5])  func containsduplicatesset(a: [int]) -> bool {     return set(a).count != a.count }  containsduplicatesset(a: [1,2,2,4]) 

the first function, containsduplicatesdictionary, convert array dictionary, of course takes loop well. set method can done in 1 line, nice. guess since new this, think converting array throw error since theres duplicate values.

what missing when it's converted

thank you.

set, design unordered, unique collection of elements. implementation of set takes care of duplicate values itself, when try add duplicate value, checks whether value present in set or not , if is, value not added.

when call initializer of set takes sequence input parameter (this use when writing set(a), a of type [int], under hood, initializer adds elements 1 one checking whether of new elements present in set or not.

you make custom initializer method set throw error if try add duplicate value it, wouldn't have advantages users of swift, hence current implementation doesn't add value if present in set , doesn't throw error. way, can safely , rid of duplicates in non-unique collection of elements (such array).


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -