Swift-将数组转换为字典 [英] Swift - Convert Array to Dictionary

查看:1047
本文介绍了Swift-将数组转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想将一组玩家名称转换成字典记分板,使每个人的初始分数都为0.

I just want convert an array of Player Names into a dictionary Scoreboard, giving everyone an initial score of 0.

含义...

var playerNames = ["Harry", "Ron", "Hermione"]

成为 ...

var scoreBoard: [String:Int] = [ "Ron":0, "Harry":0, "Hermione":0 ]

这是我第一次问一个问题,但是我完全陷入了如此简单的感觉,而我发现的所有使用方法/问题"都以某种方式存在.我尝试过以各种方式使用reduce,但是总是以失败告终.预先感谢!

This is my first time asking a question, but I’m totally completely stuck on what feels so simple and all how-to's/questions I've found are off in some way. I have tried using reduce in a variety of ways, but always end up short. Thanks in advance!

推荐答案

这里是我想使用的快速衬纸:

Here's a quick one liner that I like to use:

let scoreboard = playerNames.reduce(into: [String: Int]()) { $0[$1] = 0 }

这篇关于Swift-将数组转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆