Create a Swift Dictionary Subclass

Create a Swift Dictionary subclass?

Swift dictionaries are structs, not classes, so they cannot be subclassed. Ideally, the methods you're working with would be declared to take an appropriately constrained generic CollectionType (or ExtensibleCollectionType, or SequenceType, depending on the situation), rather than specifically a Dictionary.

If that doesn't work for you for whatever reason, you could subclass NSDictionary instead.

(edit) and as Antonio points out, you can do extension Dictionary { … } to add things to the Dictionary struct, which can replace subclassing in some cases.

Create a dictionary of generic variables in swift

variable1 and variable2 are not of type Entity but are in fact Entity<Float> and Entity<String> which are two unrelated types. Use a protocol to unite them:

protocol EntityProtocol { }

class Entity<T> : EntityProtocol {
var _value: T
var value: T { get { return _value } set {_value = newValue}}

init (defaultValue: T) {
_value = defaultValue
}
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
let variable1: Entity = FloatEntity (defaultValue: 1)
let variable2: Entity = StringEntity (defaultValue: "")
var dictionary: Dictionary<String, EntityProtocol> = [
"One": FloatEntity (defaultValue: 1),
"Two": StringEntity (defaultValue: ""),
]
print (variable1)
print (variable2)
print (dictionary)
}

Create dictionary with values that inherit from a superclass

Assuming that GoogleView and DuckDuckGoView inherit from EngineView you can do something like this:

let map = [String: EngineView.Type] = [
"google": GoogleView.self,
"duckduckgo": DuckDuckGoView.self
]

Usage

if let aClass = map["google"] {
let instance = aClass.init()
}

Can I use a swift dictionary in a subclass of AWSDynamoDBModel?

Currently, AWSDynamoDBObjectMapper supports:

  1. NSNumber
  2. NSString
  3. NSData
  4. NSArray of the above three datatypes

NSDictionary is not supported, but we are evaluating how we can support the map datatype in the coming releases.

Create a Swift Object from a Dictionary

Hopefully this is useful to others. It took some research to figure this out. The goal is to avoid the anti-pattern of giant if or switch statements to create each object type from a value.

class NamedItem : CustomStringConvertible {
let name : String

required init() {
self.name = "Base"
}

init(name : String) {
self.name = name
}

var description : String { // implement Printable
return name
}
}

class File : NamedItem {
required init() {
super.init(name: "File")
}
}

class Folder : NamedItem {
required init() {
super.init(name: "Folder")
}
}

// using self to instantiate.
let y = Folder.self
"\(y.init())"

let z = File.self
"\(z.init())"

// now put it in a dictionary.
enum NamedItemType {
case folder
case file
}

var typeMap : [NamedItemType : NamedItem.Type] = [.folder : Folder.self,
.file : File.self]
let p = typeMap[.folder]
"\(p!.init())"
let q = typeMap[.file]
"\(q!.init())"

Interesting aspects:

  • use of "required" for initializers
  • use of .Type to get the type for the dictionary value.
  • use of .self to get the "class" that can be instantiated
  • use of () to instantiate the dynamic object.
  • use of Printable protocol to get implicit string values.
  • how to init using a non parameterized init and get the values from subclass initialization.

Updated to Swift 3.0 syntax

Custom sequence for Swift Dictionary

If I'm understanding correctly, how about just forwarding on the generate?

func generate() -> DictionaryGenerator<String, STCQuestion> {
return questionDict.generate()
}

(You don't need to implement GeneratorType, just SequenceType should do. It's generate() itself that returns a GeneratorType, and that's what has to implement next(), which the existing generate() implementation in Dictionary already does for you.)

Full worked example based on your code:

// Playground - noun: a place where people can play

import Foundation

class STCQuestion {
let foo: String
init(_ foo: String) {
self.foo = foo
}
}

class STCQuestionList : SequenceType {

private var questionDict: [String : STCQuestion] = [ : ];

subscript(key : String?) -> STCQuestion? {
get {
if key != nil {
return self.questionDict[key!];
}
return nil;
}
set(newValue) {
if key != nil {
self.questionDict[key!] = newValue;
}
}
}

func generate() -> DictionaryGenerator<String, STCQuestion> {
return questionDict.generate()
}
}

var list = STCQuestionList()
list["test"] = STCQuestion("blah")
list["another"] = STCQuestion("wibble")
list["third"] = STCQuestion("doodah")

for (key, value) in list {
println("Key: \(key) Foo: \(value.foo)")
}

// Output:
// Key: test Foo: blah
// Key: another Foo: wibble
// Key: third Foo: doodah


Related Topics



Leave a reply



Submit