GVKun编程网logo

Swift:flatMap to Dictionary

1

本篇文章给大家谈谈Swift:flatMaptoDictionary,同时本文还将给你拓展DictionaryObjectIdentifier:CustomClassQuestionsaboutDic

本篇文章给大家谈谈Swift:flatMap to Dictionary,同时本文还将给你拓展Dictionary ObjectIdentifier: CustomClass Questions about Dictionary append in Swift、flatMap 和 flatMap 单个用于分组的 observables、Flux.parallel.runOn().flatMap(blockingcall //Mono.fromCallable) 与flux.flatMap(blockingcall.subscribeOn() //Mono.fromCallable) 的区别、GridQueryableCollectionViewWrapper 将我的 Dictionary 转换为 Dictionary for SfDataGrid等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

Swift:flatMap to Dictionary

Swift:flatMap to Dictionary

我试图解析以下 JSON:

{ 
  "String For Key 1": [
    "Some String A","Some String B","Some String C",],"String For Key 2": [
    "Some String D","Some String E","Some String F"
  ],"String For Key 3": [
    "Some String G","Some String H","Some String I","String For Key 4": [
    "Some String J","Some String K","Some String L"
  ],"String For Key 5": [
    "Some String M","Some String N","Some String O"
  ],"String For Key 6": [
    "Some String P","Some String Q","Some String R"
  ]
}

我也关注这个tutorial.它在Playground的Github上

在示例中,他们使用typealias JSONDictionary = [String:AnyObject]解析字典数组

我需要解析一个具有Key的字典,这个字符串是String,而Value是一个Array.因此:typealias JSONDictionary = [String:[AnyObject]],我在返回flatMap时遇到错误.

extension Resource {
    init(url: NSURL,parseJSON: AnyObject -> A?) {
        self.url = url
        self.parse = { data in
            let json = try? NSJSONSerialization.JSONObjectWithData(data,options: []) as? [String: [AnyObject]]
           //This is where I get an error
            return json.flatMap(parseJSON)
        }
    }
}

错误:

Cannot convert value of type `AnyObject -> A? to expected argument type `([String: [AnyObject]]?) -> _?

如何获得一个字符串,字符串为String,值为数组?我想保留他们的通用方法.

解决方法

jsonString的类型是Dictionary< String,Array< String>>
你可以给它一个像Dictionary< String,AnyObject>这样的类型.

AnyObject可以包含类和结构,即Array,Dictionary,String,Int,Obj C Classes
因此,一个数组< String>由AnyObject表示而不是[AnyObject]

let jsonString:[String: AnyObject] =
[
    "String For Key 1": [
    "http://www.urlToSomePathA.jpg","http://www.urlToSomePathB.jpg","http://www.urlToSomePathC.jpg","String For Key 2": [
    "http://www.urlToSomePathD.jpg","http://www.urlToSomePathE.jpg","http://www.urlToSomePathF.jpg"
    ]
]

// Now you can map a function on the value type
let values = jsonString.flatMap { $0.1 as? [String] }
print(values)
// RESULT: [["http://www.urlToSomePathA.jpg","http://www.urlToSomePathC.jpg"],["http://www.urlToSomePathD.jpg","http://www.urlToSomePathF.jpg"]]

更新

let keys = jsonString.flatMap { $0.0 } // ["String For Key 1","String For Key 2"]

正如@dffri所评论的那样,你可以在字典上使用keys属性,它将返回LazyMapCollection,只有当你访问里面的对象时才会实现.

let keys = jsonString.keys

Dictionary ObjectIdentifier: CustomClass Questions about Dictionary append in Swift

Dictionary ObjectIdentifier: CustomClass Questions about Dictionary append in Swift

如何解决Dictionary ObjectIdentifier: CustomClass Questions about Dictionary append in Swift

嗨?我创建了 BananaMilkFactoryciderFactoryCantataCoffeeFactory,它们继承了名为 Beverage 的超类。我制作了一个库存,将饮料打包成一个数组。

例如,如果您创建 3 个香蕉牛奶、2 个苹果酒、1 个康塔塔咖啡,则库存将总共有 6 个饮料。

我想要的函数是[ObjectIdentifier: Inventory],我想分别返回同一个ObjectIdentifier的Beverages。


// [BananaMilk(),BananaMilk(),cider(),CantataCoffee()]
private var inventory: [Beverage]

func readInventores() -> [ObjectIdentifier : Inventory] {
    var allInventores = [ObjectIdentifier : Inventory]()

    self.inventory.forEach { beverage in
        // Help~!!
    }
            
    return allInventores
}

我应该怎么做才能以 [ObejctIdentifier: Inventory] ​​格式返回?

解决方法

创建一个数组,其中包含对象的类名(BananaMilkFactory、CiderFactory ....)。遍历数组,将类名相同的对象放到一个新数组中。不知道我理解的对不对。

flatMap 和 flatMap 单个用于分组的 observables

flatMap 和 flatMap 单个用于分组的 observables

如何解决flatMap 和 flatMap 单个用于分组的 observables

我是 RxJava 的新手并试图理解它。我有以下来源:

  1. Observable<Employee> obs = Observable.just(
  2. new Employee(101,"Jim",68_000,4.2),new Employee(123,"Bill",194_000,6.7));
  3. obs.groupBy(e -> e.getrating())
  4. .flatMapSingle(e -> e.toMultimap(key -> e.getKey(),emp -> emp.getName()))
  5. .subscribe(System.out::println);

这种方法打印键和关联的值。
如果我这样做:

  1. obs.groupBy(e -> e.getrating())
  2. .flatMapSingle(e -> e.toList())
  3. .subscribe(System.out::println);

它似乎打印了与键关联的值列表。
但是 flatMapSingle 究竟是如何工作的?与 flatMap 有什么区别?

解决方法

来自文档:

  1. Maps each element of the upstream {@code Flowable} into {@link SingleSource}s,subscribes to all of them
  2. * and merges their {@code onSuccess} values,in no particular order,into a single {@code Flowable} sequence.

它在两种情况下都以相同的方式工作。 当你调用

  1. flatMapSingle(e -> { // convert to some value})

您将“e”转换为 lambda 返回的值。 在您的情况下,“e”是 GroupedFlowable

在第一种情况下,您将所有元素转换为包含条目(键,值)的映射,在第二种情况下,您将其转换为列表。 flatMapSingle() 方法在这两种情况下的工作方式相同。

您得到不同的结果,因为您使用了不同的 Function 实现并将其作为参数传递给 flatMapSingle

Function 参数在你的例子中看起来像 e -> { .... } 决定了如何处理由源发出的元素的方式。

Flux.parallel.runOn().flatMap(blockingcall //Mono.fromCallable) 与flux.flatMap(blockingcall.subscribeOn() //Mono.fromCallable) 的区别

Flux.parallel.runOn().flatMap(blockingcall //Mono.fromCallable) 与flux.flatMap(blockingcall.subscribeOn() //Mono.fromCallable) 的区别

如何解决Flux.parallel.runOn().flatMap(blockingcall //Mono.fromCallable) 与flux.flatMap(blockingcall.subscribeOn() //Mono.fromCallable) 的区别

flux 发出的元素的生成并行计算的以下实现有什么区别。

  1. Flux.fromIterable(list)
  2. .parallel()
  3. .runOn(Schedulers.boundedElastic())
  4. .flatMap(items -> Mono.fromCallable(() -> blocking database call).subscribeOn(Schedulers.boundedElastic()))
  5. .map(dbResponse -> dbResponse.stream().map(singleObj-> createAdifferentObject(dbResponse)).collect(Collectors.toList())
  6. .block()

  1. Flux.fromIterable(list)
  2. .flatMap(items -> Mono.fromCallable(() -> blocking database call).subscribeOn(Schedulers.boundedElastic()))
  3. .map(dbResponse -> dbResponse.stream().map(singleObj-> createAdifferentObject(dbResponse)).collect(Collectors.toList())
  4. .block()

对于第一段代码,我引用了这个块

  1. return Flux.fromIterable(urls)
  2. .flatMap(url ->
  3. //wrap the blocking call in a Mono
  4. Mono.fromCallable(() -> blockingWebClient.get(url))
  5. //ensure that Mono is subscribed in an boundedElastic Worker
  6. .subscribeOn(Schedulers.boundedElastic())
  7. ); //each individual URL fetch runs in its own thread!
  8. }

来自此博客 https://spring.io/blog/2019/12/13/flight-of-the-flux-3-hopping-threads-and-schedulers

对于第二段代码,一般在我们的团队或组织中,每个人都会使用它。这个文档说,调度程序。(没有新词)从这个链接 https://projectreactor.io/docs/core/release/api/reactor/core/scheduler/Schedulers.html 创建一个共享实例,但就流程而言,这不应该在 flatMap 之外吗?如果不是,它是如何工作的?

GridQueryableCollectionViewWrapper 将我的 Dictionary<string,object> 转换为 Dictionary<string,string> for SfDataGrid

GridQueryableCollectionViewWrapper 将我的 Dictionary 转换为 Dictionary for SfDataGrid

如何解决GridQueryableCollectionViewWrapper 将我的 Dictionary<string,object> 转换为 Dictionary<string,string> for SfDataGrid

我正在实施以下建议,以在 Xamarin Forms 中将字典绑定到我的 SfDataGrid (v 19.1451.0.54)。

我正在像这样设置我的网格 ItemsSource:

grid.ItemsSource = new QueryableViewExt(rows,grid);

其中行是基于此示例的 ObservableCollection<DynamicModel> 类型:https://www.syncfusion.com/kb/7829/how-to-load-sfdatagrid-dynamically-with-json-data-without-poco-classes

问题出在 QueryableViewExt 类中。当这个类被初始化(构造函数调用)时,我看到源字典按预期作为 Dictionary<string,object> 进入,但是当我点击我的网格列进行排序时,当它到达 GetExpressionFunc 方法时,我可以在调试源更改时看到到 Dictionary<string,string> 出于某种原因,它没有正确排序我的整数。

知道为什么字典类型会发生变化吗?

类定义:

QueryableViewExt

  1. public class QueryableViewExt : GridQueryableCollectionViewWrapper
  2. {
  3. public QueryableViewExt(IEnumerable source,SfDataGrid grid) : base(source,grid)
  4. {
  5. }
  6. public override Expression> GetExpressionFunc(string propertyName,DataOperation operation = DataOperation.Default,DataReflectionMode reflectionMode = DataReflectionMode.Default)
  7. {
  8. Expression> exp = base.GetExpressionFunc(propertyName,operation,reflectionMode);
  9. if (exp == null)
  10. {
  11. Func func;
  12. func = (propertyname,record) =>
  13. {
  14. var provider = this.GetPropertyAccessprovider();
  15. return provider.GetValue(record,propertyName);
  16. };
  17. exp = (propertyname,record) => func(propertyName,record);
  18. }
  19. return exp;
  20. }
  21. }

动态模型

  1. public class DynamicModel : INotifyPropertyChanged
  2. {
  3. public Dictionary<string,object> data;
  4. public event PropertyChangedEventHandler PropertyChanged;
  5. public Dictionary<string,object> Values
  6. {
  7. get
  8. {
  9. return data;
  10. }
  11. set
  12. {
  13. data = value;
  14. if (PropertyChanged != null)
  15. PropertyChanged(this,new PropertyChangedEventArgs("Values"));
  16. }
  17. }
  18. public DynamicModel()
  19. {
  20. this.data = new Dictionary<string,object>();
  21. }
  22. }

解决方法

我想我已经想通了,以防有人遇到同样的问题。

我从这个 Syncfusion post 中获取了代码片段,以编程方式构建我的网格列数据模板。用 SfLabel 替换 Label 对我有用。现在数字排序按预期工作

原始代码

  1. var dataTemplate = new DataTemplate(()=>
  2. {
  3. var label = new SfLabel()
  4. {
  5. TextColor = Color.Blue,VerticalOptions = LayoutOptions.Center,HorizontalOptions=LayoutOptions.Center
  6. };
  7. label.SetBinding(SfLabel.TextProperty,$"Values[{kvp.Key}]");
  8. return label;
  9. });

新代码:

  1. var dataTemplate = new DataTemplate(()=>
  2. {
  3. var label = new Label()
  4. {
  5. TextColor = Color.Blue,HorizontalOptions=LayoutOptions.Center
  6. };
  7. label.SetBinding(Label.TextProperty,$"Values[{kvp.Key}]");
  8. return label;
  9. });

我在 this Syncfusion post 中询问他们是否知道 SfLabel 的行为不同的原因。

我们今天的关于Swift:flatMap to Dictionary的分享已经告一段落,感谢您的关注,如果您想了解更多关于Dictionary ObjectIdentifier: CustomClass Questions about Dictionary append in Swift、flatMap 和 flatMap 单个用于分组的 observables、Flux.parallel.runOn().flatMap(blockingcall //Mono.fromCallable) 与flux.flatMap(blockingcall.subscribeOn() //Mono.fromCallable) 的区别、GridQueryableCollectionViewWrapper 将我的 Dictionary 转换为 Dictionary for SfDataGrid的相关信息,请在本站查询。

本文标签: