스위프트를 어레이로 설정
는 NSSet
변환 될 수 Array
사용 set.allObjects()
하지만 새에서 이러한 방법이 없다 Set
(SWIFT 1.2 도입이). 스위프트 세트를 NSSet로 변환하고 allObjects()
방법을 사용하여 여전히 수행 할 수 있지만 최적은 아닙니다.
주어진 Swift의 모든 요소를 사용하여 Set
간단히 배열을 만들 수 있습니다.
let array = Array(someSet)
이것은 프로토콜을 Set
준수 하고 시퀀스로 초기화 할 수 있기 때문에 작동 합니다. 예:SequenceType
Array
let mySet = Set(["a", "b", "a"]) // Set<String>
let myArray = Array(mySet) // Array<String>
print(myArray) // [b, a]
가장 간단한 경우 , 스위프트 3, 당신은 사용할 수 Array
의 init(_:)
를 얻기 위해 초기화를 Array
A로부터 Set
. init(_:)
다음과 같은 선언이 있습니다.
init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element
시퀀스의 요소를 포함하는 배열을 만듭니다.
용법:
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = Array(stringSet)
print(stringArray)
// may print ["toy", "car", "bike", "boat"]
그러나 , 당신은 또한의 각 요소에 대해 일부 작업을 수행하려는 경우 Set
로 변환이 동안 Array
, 당신이 사용할 수있는 map
, flatMap
, sort
, filter
과에서 제공하는 다른 기능 방법 Collection
프로토콜 :
let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = stringSet.sorted()
print(stringArray)
// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = stringSet.filter { $0.characters.first != "b" }
print(stringArray)
// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2])
let stringArray = intSet.flatMap { String($0) }
print(stringArray)
// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])
// alternative to `let intArray = Array(intSet)`
let intArray = intSet.map { $0 }
print(intArray)
// may print [5, 2, 3, 1]
추가 :
Swift에는 Set 및 Dictionary에 대한 DEFINED ORDER 가 없습니다. 따라서 sorted () 메서드를 사용하여 배열이 ""a ","b "] 또는 ["b "," "]하고 싶지 않습니다.
이 문제를 해결하려면 :
세트
var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray
결과 : [ "a", "b", "c"]
sorted ()없이
그것은 될 수 있습니다:
["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"]
간단한 수학 : 3! = 6
나는 당신에게 정렬되지 않은를 제공하는 간단한 확장 생성 Array
의 속성으로 Set
의 스위프트 4.0 .
extension Set {
var array: [Element] {
return Array(self)
}
}
If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
let array = set.array
The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:
for item in myItemSet {
...
}
Or, to use the "sorted" method:
let itemsArray = myItemSet.sorted()
It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.
If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:
let itemsArray = myItemSet.map { $0 }
Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:
var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
itemsArray = typedSet.map { $0 }
}
call this method and pass your set
func getArrayFromSet(set:NSSet)-> NSArray {
return set.map ({ String($0) })
}
Like This :
var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))
참고URL : https://stackoverflow.com/questions/29046695/swift-set-to-array
'IT' 카테고리의 다른 글
Git 사용자를위한 Perforce? (0) | 2020.06.01 |
---|---|
현재 지점에서 커밋 할 것이 없는지 확인하는 방법은 무엇입니까? (0) | 2020.06.01 |
복합 기본 키를 올바르게 작성하는 방법-MYSQL (0) | 2020.06.01 |
base64로 인코딩 된 문자열에 대한 ArrayBuffer (0) | 2020.06.01 |
DIV를 포장하지 않는 방법? (0) | 2020.06.01 |