简体   繁体   English

比较Swift和Python字典对象

[英]Comparing Swift and Python Dictionary objects

I'm trying to get familiar with Swift, so I'm doing some basic computations that I would normally do in Python. 我试图熟悉Swift,所以我正在做一些通常在Python中执行的基本计算。

I want to get a value from a dictionary using a key. 我想使用键从字典中获取值。 In Python I would simply : 在Python中,我将简单地:

sequences = ["ATG","AAA","TAG"]
D_codon_aa = {"ATG": "M", "AAA": "R", "TAG": "*"}
for seq in sequences:
    print D_codon_aa[seq]
>>>
M
R
*

When I try this in Swift. 当我在Swift中尝试这个时。

let sequences = ["ATG","AAA","TAG"]
let D_codon_aa = ["ATG": "M", "AAA": "R", "TAG": "*"]
for seq in sequences
    {
    var codon = D_codon_aa[seq]
    println(codon)
    }
>>>
Optional("M")
Optional("R")
Optional("*")

1) What is Optional() and why is it around the dictionary value? 1)什么是Optional(),为什么它在字典值的周围?

2) Why can't I make a dictionary with multiple types of objects inside? 2)为什么我的字典不能包含多种类型的对象?

In Python I can do this: 在Python中,我可以这样做:

sequence= {'A':0,'C':1, 'G':'2', 'T':3.0}

In Swift I can't do this: 在Swift中,我无法做到这一点:

let sequences = ["A":0,"C":1, "G":"2", "T":3.0]

1: Look at the declaration of the dictionarys subscript: 1:看一下字典下标的声明:

subscript(key: Key) -> Value?

It returns an optional, since you can use any key you want in subscripts, but they might not associated with values, so in that case it returns nil, otherwise the value wrapped in an optional. 它返回一个可选值,因为您可以在下标中使用所需的任何键,但是它们可能不与值关联,因此在这种情况下,它返回nil,否则将值包装在可选值中。

2: Actually, you can, if you define your dictionary as for eg. 2:实际上,如果您将字典定义为例如。 ["String": AnyObject], and now you can associate keys with values, thats conforms to the AnyObject protocol. [“ String”:AnyObject],现在您可以将键与值相关联,这符合AnyObject协议。

Updated And your example let sequences = ["A":0,"C":1, "G":"2", "T":3.0] compiles fine in Xcode 6.1.1. 更新 ,您的示例let sequences = ["A":0,"C":1, "G":"2", "T":3.0]在Xcode 6.1.1中可以正常编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM