사전 키에서 빠르게 배열
사전에 있는 키의 문자열을 빠르게 배열에 채우려고 합니다.
var componentArray: [String]
let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!)
componentArray = dict.allKeys
문자열과 같지 않은 오류 'AnyObject'가 반환됩니다.
시도했다
componentArray = dict.allKeys as String
get: 'String'은 [String]으로 변환할 수 없습니다.
Swift 3 & Swift
componentArray = Array(dict.keys) // for Dictionary
componentArray = dict.allKeys // for NSDictionary
Swift 3에서는Dictionary속성을 가지고 있습니다. keys에는 다음 선언이 있습니다.
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
사전의 키만 포함하는 컬렉션입니다.
이는 쉽게 매핑할 수 있습니다.Array와 함께Array이니셜라이저
부터NSDictionary로.[String]
다음 iOSAppDelegateclass snippet은 문자열 배열을 가져오는 방법을 보여 줍니다.[String])의 사용keys로부터의 재산NSDictionary:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let string = Bundle.main.path(forResource: "Components", ofType: "plist")!
if let dict = NSDictionary(contentsOfFile: string) as? [String : Int] {
let lazyMapCollection = dict.keys
let componentArray = Array(lazyMapCollection)
print(componentArray)
// prints: ["Car", "Boat"]
}
return true
}
부터[String: Int]로.[String]
보다 일반적인 방법으로 다음 Playground 코드는 문자열 배열을 얻는 방법을 보여줍니다.[String])의 사용keys문자열 키 및 정수 값을 사용하여 사전의 속성([String: Int]):
let dictionary = ["Gabrielle": 49, "Bree": 32, "Susan": 12, "Lynette": 7]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection)
print(stringArray)
// prints: ["Bree", "Susan", "Lynette", "Gabrielle"]
부터[Int: String]로.[String]
다음 Playground 코드는 문자열 배열을 가져오는 방법을 보여 줍니다.[String])의 사용keys사전에서 정수 키와 문자열 값을 가진 속성([Int: String]):
let dictionary = [49: "Gabrielle", 32: "Bree", 12: "Susan", 7: "Lynette"]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection.map { String($0) })
// let stringArray = Array(lazyMapCollection).map { String($0) } // also works
print(stringArray)
// prints: ["32", "12", "7", "49"]
Swift 사전 키 배열
componentArray = [String] (dict.keys)
dictionary.map은 다음과 같이 사용할 수 있습니다.
let myKeys: [String] = myDictionary.map{String($0.key) }
설명:myDictionary를 반복하여 각 키와 값의 쌍을 $0으로 받아들입니다.여기서 $0.key 또는 $0.value를 얻을 수 있습니다.후행 폐쇄 {} 내에서 각 요소를 변환하고 해당 요소를 반환할 수 있습니다.$0을 원하는 경우 문자열로 변환해야 하므로 String(0.key)을 사용하여 변환합니다.변환된 요소를 문자열 배열로 수집합니다.
dict.allKeys문자열이 아닙니다.그것은 이다.[String]이 에러 메세지가 나타내는 대로입니다(물론, 키는 모두 스트링입니다.이것이, 그 말을 할 때의 어설션입니다).
그럼, 먼저 타이핑으로 시작하든가componentArray~하듯이[AnyObject]왜냐하면 그게 코코아 API에 입력되는 방법이기 때문이다. 혹은 당신이 캐스트를 한다면dict.allKeys, 그것을 에 던지다.[String]그렇게 입력했기 때문입니다.componentArray.
extension Array {
public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
var dict = [Key:Element]()
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}
dict.keys.sorted()
[String] https://developer.apple.com/documentation/swift/array/2945003-sorted 를 제공합니다.
Array Apple 공식 문서에서 다음 문서를 참조하십시오.
init(_:)- 시퀀스의 요소를 포함하는 배열을 만듭니다.
선언.
Array.init<S>(_ s: S) where Element == S.Element, S : Sequence
파라미터
s - 배열로 변환하는 요소의 시퀀스.
논의
이 이니셜라이저를 사용하여 시퀀스 프로토콜을 준수하는 다른 유형의 배열을 만들 수 있습니다.이 이니셜라이저를 사용하여 복잡한 시퀀스 또는 수집 유형을 다시 배열로 변환할 수도 있습니다.예를 들어 사전의 키 속성은 자체 스토리지가 있는 배열이 아니라 액세스할 때만 사전에서 요소를 매핑하는 컬렉션이므로 어레이 할당에 필요한 시간과 공간을 절약할 수 있습니다.그러나 이러한 키를 배열을 사용하는 메서드에 전달해야 하는 경우 이 이니셜라이저를 사용하여 목록을 다음 유형에서 변환합니다.
LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].
func cacheImagesWithNames(names: [String]) {
// custom image loading and caching
}
let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
"Gold": 50, "Cerise": 320]
let colorNames = Array(namedHues.keys)
cacheImagesWithNames(colorNames)
print(colorNames)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
스위프트 5
var dict = ["key1":"Value1", "key2":"Value2"]
let k = dict.keys
var a: [String]()
a.append(contentsOf: k)
난 이거면 돼.
NSDictionary는 클래스(참조 기준) 사전은 구조(값 기준) ====== NSDictionary의 배열 ======
NSDictionary에는 allKeys가 있으며 allValues는 유형이 [Any]
인 속성을 가져옵니다.
let objesctNSDictionary =
NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
====== 사전에서 배열 ======
let objectDictionary:Dictionary =
["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)
let objectArrayOfAllValues:Array = Array(objectDictionary.values)
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
이 답은 String 키가 있는 swift 사전입니다.아래 이렇게.
let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]
여기 제가 사용할 내선번호가 있습니다.
extension Dictionary {
func allKeys() -> [String] {
guard self.keys.first is String else {
debugPrint("This function will not return other hashable types. (Only strings)")
return []
}
return self.flatMap { (anEntry) -> String? in
guard let temp = anEntry.key as? String else { return nil }
return temp }
}
}
그리고 열쇠는 나중에 이걸로 다 가져올게요.
let componentsArray = dict.allKeys()
// Old version (for history)
let keys = dictionary.keys.map { $0 }
let keys = dictionary?.keys.map { $0 } ?? [T]()
// New more explained version for our ducks
extension Dictionary {
var allKeys: [Dictionary.Key] {
return self.keys.map { $0 }
}
}
언급URL : https://stackoverflow.com/questions/26386093/array-from-dictionary-keys-in-swift
'programing' 카테고리의 다른 글
| 태그 또는 태그 부착에 권장되는 SQL 데이터베이스 설계 (0) | 2023.04.14 |
|---|---|
| matplotlib에서 축 문자 회전 (0) | 2023.04.14 |
| 다중 바인딩에서 1개의 바인딩에 대해 상수 값을 전달하려면 어떻게 해야 합니까? (0) | 2023.04.09 |
| SQL Server ': setvar' 오류 (0) | 2023.04.09 |
| WPF: 스크롤바가 있는 항목 제어(ScrollViewer) (0) | 2023.04.09 |


