如何在Swift中扩展数组?

时间:2016-06-09 03:40:54

标签: arrays swift protocols

我有这个协议

protocol JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue)
}

UnderlyingValueenum

enum UnderlyingValue {
    case string(String)
    case int(Int)
    case double(Double)
    case bool(Bool)
    case array(Array<Dictionary<String, AnyObject>>)
    case dictionary(Dictionary<String, AnyObject>)

    init?(value: JsonConvertable) {
        switch rawValue {
        case let value as [String: AnyObject]: self = .dictionary(value)
        case let value as Array<[String: AnyObject]>: self = .array(value)
        case let value as Double: self = .double(value)
        case let value as Int: self = .int(value)
        case let value as Bool: self = .bool(value)
        case let value as String: self = .string(value)
        default: return nil
        }
    }
}

我可以扩展大多数类型如下

extension String: JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue) {
        switch underlyingValue {
        case .bool(let value): self = value
        default: return nil
    }
}

然而,Array扩展程序给出了错误 Cannot assign value of type 'Array<Dictionary<String, AnyObject>>' to type 'Array<_>'

extension Array: JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue) {
        switch underlyingValue {
        case .array(let value): self = value
        default: return nil
        }
    }
}

我已经尝试了我能想到的一切,但没有任何工作。我试图让JsonConvertable符合ArrayLiteralConvertable,我尝试在init中使用泛型,但我刚刚开始理解泛型,并且在这种情况下我不知道它是如何有益的,与AssociatedType相同。我试图限制元素。我一直试图让这个工作整整2天,我所做的一切似乎都没有取得任何进展。我错过了什么?

1 个答案:

答案 0 :(得分:4)

在您的扩展方法中,您正在扩展Array,这是一种Array&lt; _&gt;你的_underlyingValue是Array&lt; [String:AnyObject]&gt;。

的类型

您是否尝试过这种方式:

#define _CRT_SECURE_NO_WARNINGS
#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readString(char **s)
{
int i = 0;
char c;
printf("\nInput string:     ");
while ((c = getchar()) != '\n')
{
    i++;
    *s = realloc(*s, i*sizeof(char*));
    if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
    (*s)[i - 1] = c;
}
*s = realloc(*s, (i + 1)*sizeof(char));
if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
(*s)[i] = '\0';
}


char **load_words()
{
int cnt=0,wordcnt=0,i=0;
char **words = NULL, *input = NULL; 
readString(&input);
while (input[cnt] != '\0' && cnt < strlen(input))
{
    words = realloc(words, ++wordcnt);//errors in second repeat of the loop
    words[wordcnt] = malloc(MAX);
    i = 0;
    while (input[cnt] != ' ')
    {
        words[wordcnt][i++] = input[cnt++];
    }
    words[wordcnt][i] = '\0';
    realloc(words[wordcnt], (i + 1)*sizeof(char));
}
realloc(words, wordcnt);
free(input);
return words;
}

void main()
{
 int i;
 char **words = NULL;
 words = load_words();
 scanf("%d", &i);
}