Custom sequence for Swift Dictionary - ios

I have a container class that has an underlying dictionary. I have implemented subscripts for this class to access member of the underlying dictionary. Now, I am trying to create a sequence on this class so that I could iterate over all the elements of the underlying dictionary by using 'for-in' loop on the class instance itself. I have been looking to find some examples for Sequences for Swift Dictionary but could not find anything that explains the stuff well. I have seen some custom sequence examples for Swift Array but none for the Swift Dictionary. I would really appreciate if anyone could explain how I can achieve that. Following is the code for the class (no sequence code yet as I am not sure where to begin)
import Foundation
class STCQuestionList : GeneratorType, 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() -> GeneratorType {
}
func next() -> (String, STCQuestion)? {
if (self.questionDict.isEmpty) {
return .None
}
}
}

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

(Note: I re-thought this -- original answer via the edited page...)
Swift has a generic GeneratorOf type that you can use to create a generator. You just provide a closure that returns the next value in the initializer:
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;
}
}
}
/// Creates a generator for each (key, value)
func generate() -> GeneratorOf<(String, STCQuestion)> {
var index = 0
return GeneratorOf<(String, STCQuestion)> {
if index < self.questionDict.keys.array.count {
let key = self.questionDict.keys.array[index++]
return (key, self.questionDict[key]!)
} else {
return nil
}
}
}
}

If you don't care about the order, can't you just call the same methods of dictionary or make your class a subclass of a dictionary? For example:
func generate() -> GeneratorType {
return self.questionDict.generate()
}
func next() -> (String, STCQuestion)? {
return self.questionDict.next()
}

Related

Instantiating classes stored in metatype Dictionary

I've followed the solution at Make a Swift dictionary where the key is "Type"? to create dictionaries that can use a class type as keys.
What I want to do is: I have one dictionary that should store class types with their class type (aka metatype) as keys, too:
class MyScenario {
static var metatype:Metatype<MyScenario> {
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
Then I have methods to register and execute scenarios:
public func registerScenario(scenarioID:MyScenario.Type) {
if (scenarioClasses[scenarioID.metatype] == nil) {
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type) {
if let scenarioClass = scenarioClasses[scenarioID.metatype] {
let scenario = scenarioClass()
}
}
... Problem is in the last line:
Constructing an object of class type 'MyScenario' with a metatype
value must use a 'required' initializer.
It looks like the compiler is confused at that point since I cannot use 'required' at that assignment. Does anyone have an idea how I would have to instantiate the scenarioClass in executeScenario()?
This must do the job.
import Foundation
struct Metatype<T> : Hashable
{
static func ==(lhs: Metatype, rhs: Metatype) -> Bool
{
return lhs.base == rhs.base
}
let base: T.Type
init(_ base: T.Type)
{
self.base = base
}
var hashValue: Int
{
return ObjectIdentifier(base).hashValue
}
}
public class MyScenario
{
var p: String
public required init()
{
self.p = "any"
}
static var metatype:Metatype<MyScenario>
{
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
public func registerScenario(scenarioID:MyScenario.Type)
{
if (scenarioClasses[scenarioID.metatype] == nil)
{
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type)
{
if let scenarioClass = scenarioClasses[scenarioID.metatype]
{
let scenario = scenarioClass.init()
print("\(scenario.p)")
}
}
// Register a new scenario
registerScenario(scenarioID: MyScenario.self)
// Execute
executeScenario(scenarioID: MyScenario.self)
// Should print "any"

SequenceType with DictionaryGenerator - issues with Struct when Class works fine?

Following up on a great response here (https://stackoverflow.com/a/25322949/5583125) regarding SequenceTypes and dictionaries.
I'm using: Xcode 7.2 and Swift 2.1
Update: To clarify, I'm running this in a Playground
This works great when the child item in the embedded dictionary is a Class, but I'm experiencing issues when using a Struct - and I'm not understanding why that is.
Works great:
class Item {
let title: String
init(_ title: String) {
self.title = title
}
}
class ItemList : SequenceType {
private var itemDict: [String : Item] = [ : ];
subscript(key : String?) -> Item? {
get {
if key != nil {
return self.itemDict[key!];
}
return nil;
}
set(newValue) {
if key != nil {
self.itemDict[key!] = newValue;
}
}
}
func generate() -> DictionaryGenerator<String, Item> {
return itemDict.generate()
}
}
var list = ItemList()
list["key1"] = Item("value1")
list["key2"] = Item("value2")
for (key, value) in list {
print("Key: \(key) Foo: \(value.title)")
}
Blows up:
When I change Item to be a Struct, the for-each blows up I get a "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" exception.
struct Item {
let title: String
init(_ title: String) {
self.title = title
}
}
//Not so happy when Item is a struct
for (key, value) in list {
print("Key: \(key) Foo: \(value.title)")
}
Could someone clue me into why this might be? I get the basic concepts described in Matt Gibson's response - but I don't understand why making Item a struct instead of a Class would break things.
Perhaps the issue is something odd about the way you're testing? I tried your code in an actual iOS app and it runs fine. Here is the complete class ViewController class file in my test:
import UIKit
struct Item {
let title: String
init(_ title: String) {
self.title = title
}
}
class ItemList : SequenceType {
private var itemDict: [String : Item] = [ : ];
subscript(key : String?) -> Item? {
get {
if key != nil {
return self.itemDict[key!];
}
return nil;
}
set(newValue) {
if key != nil {
self.itemDict[key!] = newValue;
}
}
}
func generate() -> DictionaryGenerator<String, Item> {
return itemDict.generate()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let list = ItemList()
list["key1"] = Item("value1")
list["key2"] = Item("value2")
for (key, value) in list {
print("Key: \(key) Foo: \(value.title)")
}
}
}
Runs fine, and outputs this:
Key: key1 Foo: value1
Key: key2 Foo: value2

Swift Generic Class

I have a class like this
// a.swift
public class ComServiceString<Result>: ComService<Result> {
override func execute() {
if (method == Method.GET) {
manager.GET(getUrl(),
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
self.onSuccessListener?(self.parseResult(responseObject.description))
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error: " + error.localizedDescription)
var errorSd = ComServiceError(error.localizedDescription)
if (operation.response != nil) {
errorSd.errorCode = operation.response.statusCode
}
self.onFailedListener?(errorSd)
}
)
}
}
func parseResult(result: String) -> Result? {
fatalError("This method need to be implemented")
}
}
and I extend it to a new class like this
// b.swift:
public class BranchListService<T>: ComServiceString<BranchListModel> {
override func parseResult(result: String) -> BranchListModel? {
let branchListMode = BranchListModel(stringResult: result)
return branchListMode
}
}
my BranchListModel looks like this
public class BranchListModel {
public var total = 0
public var stringResult = ""
init() {}
init (stringResult result: String) {
self.stringResult = result
if let jsonArray = JSONUtil.stringToJSONArray(result) {
if let resultObject = jsonArray[0] as? NSDictionary {
if let total = resultObject["total"] as? NSString {
self.total = total.integerValue;
}
}
}
}
}
but I got BAD_ACCESS error in this line:
let branchListMode = BranchListModel(stringResult: self.resultString)
inside parseResult function on b.swift. I'm still learning this language with trying to convert my java code to swift. Do you guys know what's wrong from the code?
I think there is a bug of the Swift compiler. I've tested a relatively-simplified code below and that crashed in the same way.
class ResultParser<T> {
func parse(result: String) -> T? { abort() }
}
class MyResultParser<T>: ResultParser<Int> {
override func parse(result: String) -> Int? {
return result.toInt()
}
}
let parser: ResultParser<Int> = MyResultParser<()>()
parser.parse("2525")
At the moment, the Swift compiler cannot correctly treat virtual functions directly receiving and/or returning values, whose type is generic. I guess the compiler regards T as a pointer (object) value whatever an actual substituted type is.
I've found a workaround to do nearly the same thing.
class Box<T> {
let raw: T
init(_ raw: T) { self.raw = raw }
}
class ResultParser<T> {
func parse(result: String) -> Box<T?> { abort() }
}
class MyResultParser<T>: ResultParser<Int> {
override func parse(result: String) -> Box<Int?> {
return Box(result.toInt())
}
}
In the code above, the returned value is wrapped in the Box<>. Box<> is an object, so that works no matter whether or not the compiler can tell value types from object types.

Generic class inheritance in Swift

I have the following class:
class BaseCache<T: Equatable>: NSObject {
var allEntities = [T]()
// MARK: - Append
func appendEntities(newEntities: [T]) {
....
}
}
Now I want to subclass it, but I get annoying error, that my type "does not conform to protocol 'Equatable'":
It seems generics in Swift are real pain-in-the-ass.
Your class definition of TrackingCache is wrong. It repeats the generic parameter:
class TrackingCache<AftershipTracking>: BaseCache<AftershipTracking> { }
It should be left out:
class TrackingCache: BaseCache<AftershipTracking> { }
This triggers the underlying swift error Classes derived from generic classes must also be generic. You can work around this issue by specifying a type parameter that is required to be or inherit from AftershipTracking:
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> { }
Full example:
class BaseCache<T: Equatable>: NSObject {
var items: [T] = []
func appendItems( items: [T]) {
self.items += items
didAppendItems()
}
func didAppendItems() {} // for overriding
}
class AftershipTracking: NSObject {
var identifier: Int
init( identifier: Int) {
self.identifier = identifier
super.init()
}
}
extension AftershipTracking: Equatable { }
func ==( lhs: AftershipTracking, rhs: AftershipTracking) -> Bool {
return lhs.identifier == rhs.identifier
}
class TrackingCache<T: AftershipTracking>: BaseCache<AftershipTracking> {
override func didAppendItems() {
// do something
}
}
let a = TrackingCache<AftershipTracking>()
let b = TrackingCache<AftershipTracking>()
a.appendItems( [AftershipTracking( identifier: 1)])
b.appendItems( [AftershipTracking( identifier: 1)])
let result = a.items == b.items // true
this should work: < swift 4 >
class TrackingCache<T: AftershipTracking>: BaseCache<T>
Another example:
protocol P {
}
class C: P {
}
class CS: C {
}
class L<T:P> {
let c: T
init(_ c: T) {
self.c = c
}
}
class LS<T:CS>:L<T> {
}
let i = LS(CS())
i.c
c is CS now.

Swift contains extension for Array

I'm trying to add an extension method in Array like so:
extension Array {
func contains(obj: T) -> Bool {
let filtered = self.filter {$0 == obj}
return filtered.count > 0
}
}
But self.filter {$0 == obj} don't work. Compiler error:
could not find an overload for '==' that accepts the supplied arguments
you don't actually need to write an extension, you can use the global func contains from the Swift library:
contains([1,2,3], 1)
Swift 1.x
As I mentioned in the comments, there is a contains function. But to answer the question of how to write an extension and what the compiler error means:
The elements in the array can't necessarily be compared with ==. You need to make sure the parameter is Equatable and you need to make sure the array element is of the same type.
extension Array {
func contains<T : Equatable>(obj: T) -> Bool {
let filtered = self.filter {$0 as? T == obj}
return filtered.count > 0
}
}
Swift 2/Xcode 7 (Beta)
Swift 2 includes SequenceType.contains, which is exactly what you were trying to create.
This is made possible by a Swift syntax that allows restricting methods to certain (e.g. Equatable) type arguments. It looks like this:
extension SequenceType where Generator.Element: Equatable {
func contains(element: Self.Generator.Element) -> Bool {
...
}
}
I found that the built-in contains doesn't work with reference types. I needed this and solved it with the code below. I'm pasting it here because somebody else might be confused about contains() like I was.
extension Array {
func containsReference(obj: AnyObject) -> Bool {
for ownedItem in self {
if let ownedObject: AnyObject = ownedItem as? AnyObject {
if (ownedObject === obj) {
return true
}
}
}
return false
}
}
This works with Swift 2.1 for reference types pretty good.
extension SequenceType where Generator.Element: AnyObject {
func contains(obj: Self.Generator.Element?) -> Bool {
if obj != nil {
for item in self {
if item === obj {
return true
}
}
}
return false
}
}
For value types you can add this:
extension SequenceType where Generator.Element: Equatable {
func contains(val: Self.Generator.Element?) -> Bool {
if val != nil {
for item in self {
if item == val {
return true
}
}
}
return false
}
}
Not perfect, but this version built on nschum's answer supports optional arguments (though not arrays with optional types) as well:
extension Array {
private func typeIsOptional() -> Bool {
return reflect(self[0]).disposition == .Optional
}
func contains<U : Equatable>(obj: U) -> Bool {
if isEmpty {
return false
}
if (typeIsOptional()) {
NSException(name:"Not supported", reason: "Optional Array types not supported", userInfo: nil).raise()
}
// cast type of array to type of argument to make it equatable
for item in self.map({ $0 as? U }) {
if item == obj {
return true
}
}
return false
}
// without this version, contains("foo" as String?) won't compile
func contains<U : Equatable>(obj: U?) -> Bool {
if isEmpty {
return false
}
if (typeIsOptional()) {
NSException(name:"Not supported", reason: "Optional Array types not supported", userInfo: nil).raise()
}
return obj != nil && contains(obj!)
}
}
If you have an array of optionals, you can get a copy of it with non-optionals (nil arguments removed) with this global function thanks to jtbandes:
func unwrapOptionals<T>(a: [T?]) -> [T] {
return a.filter { $0 != nil }.map { $0! }
}
Usage:
1> func unwrapOptionals<T>(a: [T?]) -> [T] {
2. return a.filter { $0 != nil }.map { $0! }
3. }
4>
5> let foo = ["foo" as String?]
foo: [String?] = 1 value {
[0] = "foo"
}
6> let bar = unwrapOptionals(foo)
bar: [String] = 1 value {
[0] = "foo"
}
For good measure, add one that just returns the array if its type is not optional. This way you avoid runtime errors if you call unwrapOptionals() on a non-optional array:
func unwrapOptionals<T>(a: [T]) -> [T] {
return a
}
Note you might think you could just call unwrapOptionals inside func contains<U : Equatable>(obj: U?). However, that doesn't work, because the Element type in the Array extension is just a type--it doesn't "know" it's an optional type. So if you call unwrapOptionals, the second version will be invoked, and you'll just get the array full of optionals back.

Resources