相关疑难解决方法(0)

确定Swift字典是否包含密钥并获取其任何值

我目前正在使用以下(笨拙的)代码片段来确定(非空)Swift字典是否包含给定密钥以及从同一字典中获取一个(任何)值.

怎么能把这个更优雅地放在Swift中呢?

// excerpt from method that determines if dict contains key
if let _ = dict[key] {
    return true
}
else {
    return false
}

// excerpt from method that obtains first value from dict
for (_, value) in dict {
    return value
}
Run Code Online (Sandbox Code Playgroud)

dictionary swift

238
推荐指数
4
解决办法
19万
查看次数

议定书不符合自己的要求?

为什么这个Swift代码没有编译?

protocol P { }
struct S: P { }

let arr:[P] = [ S() ]

extension Array where Element : P {
    func test<T>() -> [T] {
        return []
    }
}

let result : [S] = arr.test()
Run Code Online (Sandbox Code Playgroud)

编译器说:"类型P不符合协议P"(或者,在Swift的更高版本中,"不支持使用'P'作为符合协议'P'的具体类型.").

为什么不?不知怎的,这感觉就像语言中的漏洞.我意识到问题源于将数组声明arr为协议类型的数组,但这是不合理的事情吗?我认为协议正是为了帮助提供类似层次结构的结构?

generics swift swift-protocols

117
推荐指数
3
解决办法
1万
查看次数

为什么我不能将Protocol.Type传递给通用T.Type参数?

我正在使用Swinject,一个问题是困扰我.我差不多整整一天都被困在这里.我怀疑这是因为Swift是一种特定类型的语言,但我并不完全确定.

我在这个操场上总结了我的问题

protocol Protocol {}

class Class: Protocol {}

let test: Protocol.Type = Class.self

func printType(confromingClassType: Protocol.Type) {
    print(confromingClassType)
}

func printType<Service>(serviceType: Service.Type) {
    print(serviceType)
}

print(Class.self) // "Class"
printType(serviceType: Class.self) // "Class"
print(test) // "Class"
printType(confromingClassType: test) // "Class"

printType(serviceType: test) // "note: expected an argument list of type '(serviceType: Service.Type)'"
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的解决方案,如test.self或type(of:test),但它们都不起作用.

所以我想我不能使用作为变量提供的泛型参数来调用函数?

generics protocols swift

17
推荐指数
1
解决办法
4607
查看次数

标签 统计

swift ×3

generics ×2

dictionary ×1

protocols ×1

swift-protocols ×1