是否有CollectionType函数将集合转换为字典?

时间:2015-10-16 12:58:57

标签: swift dictionary swift2

在Swift中,是否有一个Collection函数,类似于map(),将集合转换为数组而不是字典?

我想写的一个例子:

let collection = [1, 2, 3, 4, 5] // Could also be a dictionary itself
let dictionary: [Int : String] = collection.map{
    $0 : "Number: \($0)"
}

由于我认为没有这样的功能,类似但优雅的外观怎么样?

3 个答案:

答案 0 :(得分:2)

这里有一个如何完成它的草图。它使用元素闭包的元组返回,而不是你的let collection = [1, 2, 3, 4, 5] /* OP's requested form: let dictionary: [Int : String] = collection.map{ $0 : "Number: \($0)" } */ // Return a tuple of (key, value) from the closure... extension CollectionType { func mapd<Tk: Hashable, Tv>(elementClosure: (Self.Generator.Element) -> (Tk, Tv) ) -> [Tk : Tv] { var returnDict = [Tk : Tv]() for i in self { let (k, v) = elementClosure(i) returnDict[k] = v } return returnDict } } let dictionary: [Int : String] = collection.mapd{ ($0, "Number: \($0)") } print("\(dictionary)") // "[5: "Number: 5", 2: "Number: 2", 3: "Number: 3", 1: "Number:1]" // Neither of the dictionary's elements need be the type of the collection, // it's entirely up to what the closure returns. let dictionary2: [Double : String] = collection.mapd{ (Double($0), "Number: \($0)") } print("\(dictionary)") // "[5: "Number: 5", 2: "Number: 2", 3: "Number: 3", 1: "Number:1]" 伪代码。请注意,元组元素可以是任何类型,只要第一个元素(将用作键)是可以清除的。

#!/bin/bash

echo "Please input two variables: "

read var

if var =  ' '; then
  echo var
else
  echo "More or less than two arguments"
fi

答案 1 :(得分:2)

您可以使用

extension Dictionary {
    init<S: SequenceType where S.Generator.Element == Element>(_ seq: S) {
        self.init()
        for (k,v) in seq {
            self[k] = v
        }
    }
}

this answerWhat's the cleanest way of applying map() to a dictionary in Swift?,这是非常一般的 从一系列键值对创建字典的方法。

然后您的转换可以按

完成
let collection = [1, 2, 3, 4, 5]
let dictionary = Dictionary(collection.lazy.map { ($0 , "Number: \($0)") })

print(dictionary)
// [5: "Number: 5", 2: "Number: 2", 3: "Number: 3", 1: "Number: 1", 4: "Number: 4"]

其中.lazy - 由@Kametrixom建议 - 避免创建 中间数组。

答案 2 :(得分:0)

我认为你可以使用通用函数来解决这个问题

namespace SampleWcfproject
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ISampleService1" in both code and config file together.
    [ServiceContract]
    public interface ISampleService1
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "/getdata/{uuid}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string getdata(string uuid);

         [OperationContract]
        string getcities();
}}