programing

Swift에서 고유 한 객체 목록 배열을 만드는 방법

minecode 2021. 1. 14. 08:11
반응형

Swift에서 고유 한 객체 목록 배열을 만드는 방법


우리가 어떻게 같은 스위프트 언어의 객체 목록을 만들 수 있습니다 NSSetNSMutableSet목표 - C에 있습니다.


Swift 1.2 (Xcode 6.3 베타)부터 Swift에는 기본 세트 유형이 있습니다. 릴리스 정보에서 :

Set전체 값 의미 체계와 함께 고유 한 요소의 일반 컬렉션을 제공하는 새로운 데이터 구조가 포함됩니다. 그것은과 다리 NSSet에 기능의 유사를 제공 Array하고 Dictionary.

다음은 몇 가지 간단한 사용 예입니다.

// Create set from array literal:
var set = Set([1, 2, 3, 2, 1])

// Add single elements:
set.insert(4)
set.insert(3)

// Add multiple elements:
set.unionInPlace([ 4, 5, 6 ])
// Swift 3: set.formUnion([ 4, 5, 6 ])

// Remove single element:
set.remove(2)

// Remove multiple elements:
set.subtractInPlace([ 6, 7 ])
// Swift 3: set.subtract([ 6, 7 ])

print(set) // [5, 3, 1, 4]

// Test membership:
if set.contains(5) {
    print("yes")
}

하지만 훨씬 더 많은 방법을 사용할 수 있습니다.

업데이트 : 세트는 이제 Swift 문서 "컬렉션 유형"에도 문서화되어 있습니다.


Swift에서 Objective-C 클래스를 사용할 수 있습니다.

var set = NSMutableSet()
set.addObject(foo)

Swift에는 세트 개념이 없습니다. 사용 NSMutableSet스위프트의 것은 사용하는 것보다 느려질 수 있습니다 Dictionary더미 값을 보관 유지합니다. 다음과 같이 할 수 있습니다.

var mySet: Dictionary<String, Boolean> = [:]
mySet["something"]= 1

그런 다음 키를 반복하십시오.


나는 광범위한 구축 한 Set내장과 유사한 유형 ArrayDictionary- 현재 블로그 게시물 하나, 둘, 그리고 GitHub의 저장소를 :


extension Array where Element: Hashable {
    var setValue: Set<Element> {
        return Set<Element>(self)
    }
}

let numbers = [1,2,3,4,5,6,7,8,9,0,0,9,8,7]
let uniqueNumbers = numbers.setValue    // {0, 2, 4, 9, 5, 6, 7, 3, 1, 8}

let names = ["John","Mary","Steve","Mary"]
let uniqueNames = names.setValue    // {"John", "Mary", "Steve"}

내부 사전이있는 구조체가 갈 길이라고 생각했습니다. 방금 사용하기 시작했기 때문에 완전하지 않고 성능에 대해 아직 모릅니다.

struct Set<T : Hashable>
{
    var _items : Dictionary<T, Bool> = [:]

    mutating func add(newItem : T) {
        _items[newItem] = true
    }

    mutating func remove(newItem : T) {
        _items[newItem] = nil
    }

    func contains(item: T) -> Bool {
        if _items.indexForKey(item) != nil { return true } else { return false }
    }

    var items : [T] { get { return [T](_items.keys) } }
    var count : Int { get { return _items.count } }
}

실제로 Set 객체를 매우 쉽게 만들 수 있습니다 (GoZoner와는 달리 기본 포함 메서드가 있습니다).

class Set<T : Equatable> {
    var items : T[] = []

    func add(item : T) {
        if !contains(items, {$0 == item}) {
            items += item
        }
    }
}

사용자 지정 연산자를 선언 할 수도 있습니다.

@assignment @infix func += <T : Equatable> (inout set : Set<T>, items : T[]) -> Set<T> {
    for item in items {
        set.add(item)
    }
    return set
}

Always in such a case the critical factor is how to compare objects and what types of objects go into the Set. Using a Swift Dictionary, where the Set objects are the dictionary keys, could be a problem based on the restrictions on the key type (String, Int, Double, Bool, valueless Enumerations or hashable).

If you can define a hash function on your object type then you can use a Dictionary. If the objects are orderable, then you could define a Tree. If the objects are only comparable with == then you'll need to iterate over the set elements to detect a preexisting object.

// When T is only Equatable
class Set<T: Equatable> {
  var items = Array<T>()

  func hasItem (that: T) {
   // No builtin Array method of hasItem... 
   //   because comparison is undefined in builtin Array   
   for this: T in items {
     if (this == that) {
       return true
     }
   }
   return false
  }

  func insert (that: T) {
    if (!hasItem (that))
      items.append (that)
  }
}

The above is an example of building a Swift Set; the example used objects that are only Equatable - which, while a common case, doesn't necessarily lead to an efficient Set implementations (O(N) search complexity - the above is an example).


So I think creating a Set with an array is a terrible idea - O(n) is the time complexity of that set.

I have put together a nice Set that uses a dictionary: https://github.com/evilpenguin/Swift-Stuff/blob/master/Set.swift


I wrote a function to solve this problem.

public func removeDuplicates<C: ExtensibleCollectionType where C.Generator.Element : Equatable>(aCollection: C) -> C {
    var container = C()

    for element in aCollection {
        if !contains(container, element) {
            container.append(element)
        }
    }

    return container
}

To use it, just pass an array which contains duplicate elements to this function. And then it will return a uniqueness-guaranteed array.

You also can pass a Dictionary, String or anything conforms to ExtensibleCollectionType protocol if you like.


Special case for classes derived from NSObject

given that default Equitable (& Hashable) conformance in NSObject is basically trash you'd better make sure you provide a proper

static func == (lhs: YourClassDerivedFromNSObject, rhs: YourClassDerivedFromNSObject) -> Bool {

implementation lest you want plucking the duplicates inserted into Set

ReferenceURL : https://stackoverflow.com/questions/24044190/how-to-create-array-of-unique-object-list-in-swift

반응형