天道酬勤,学无止境

Filtering dictionary in Swift 4 fails in Xcode, but succeeds in Playground

In a Swift 4 Playground this code:

let time = 1234
let description: String? = nil

let keyed: [String : Any?] = [
    "time": time,
    "description": description
    ]

let filtered: [String : String] = keyed
    .filter{ _, value in value != nil }
    .mapValues { value in return String(describing: value!) }

print(keyed)
print(filtered)

Produces this output:

["description": nil, "time": Optional(1234)]
["time": "1234"]

Which is exactly what I want (only key-value pairs where the original value is not nil, with the value unwrapped and converted to a string). However in Xcode 9 (beta 3) my build fails with 'filter' is unavailable. Is this a beta ¯\_(ツ)_/¯ kind of thing, or am I missing something?

评论

You are using Swift 3.2 instead of Swift 4.

You can change it under your target's Build Options > Swift Compiler - Language > Swift Language Version

Excerpt from Foundation's docs: https://developer.apple.com/documentation/swift/dictionary/2903389-filter?changes=latest_minor

func filter(_ isIncluded: (Dictionary.Element) throws -> Bool) rethrows -> [Dictionary.Key : Dictionary.Value]

Xcode 9.0+

I tried to resolve this a few ways, including rebooting Xcode, clearing DerivedData etc., but at the time nothing worked. I came back to the project several days later and found that the same code which had previously failed to build now built without issue (without my having made any relevant changes). So I'm blaming this on a quirk of the Xcode 9 beta. Or perhaps something was just gummed up somewhere and Xcode eventually cleared a cache or something of that nature. ¯\_(ツ)_/¯

I had the same issue today.

My project that was created in Swift 3.x with xCode 8.x. After the upgrade to xCode 9 it was working fine until today when the 'filter is unavailable' error kicked in.

Setting the Language Version explicitly to Swift 4 didn't solve it. (Neither did cleaning the project, relaunching xCode etc.)

The trick -that worked for me- was to convert to whole project to Swift 4.

(I used started with the migration tool at Edit/Convert/To current Swift syntax, which wasn't too helpful in may case but that's a completely different matter.)

After that the error was gone...

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Trouble retrieving a CGColor from a Swift dictionary
    I need a Swift dictionary that can store any kind of object. Some of the values will be CGColor references. I have no issue creating the dictionary and storing the CGColor references. The problem is trying to safely get them back. let color = CGColor(gray: 0.5, alpha: 1) var things = [String:Any]() things["color"] = color things["date"] = Date() print(things) That works and I get reasonable output. Later on I wish to get the color (which may or may not exist in the dictionary. So naturally I try the following: if let color = things["color"] as? CGColor { print(color) } But this results in the
  • Xcode 12 GM发行说明,快来看看SwiftUI和Swift都更新哪些新技术吧
    使用代码生成了词云大家可以看看 Xcode 12 GM发行说明 更新您的应用程序以使用新功能,并针对API更改测试您的应用程序。 总览 Xcode 12包括适用于iOS 14,iPad OS 14,tvOS 14,watchOS 7和macOS Catalina 10.15.6的SDK。Xcode 12 GM种子版本支持针对iOS 9和更高版本,tvOS 9和更高版本以及watchOS 2和更高版本的设备上调试。Xcode 12需要运行macOS Catalina 10.15.4或更高版本的基于Intel的Mac。 一般 新功能 现在可以在它们自己的选项卡中打开文档,从而可以轻松地在文件之间快速切换,同时保持Xcode的其余配置。按住Option键单击或双击以在选项卡中打开文档。当您打开多个文档,或者选择“视图”>“始终显示标签栏”时,将显示标签栏。(7954451) Xcode现在支持预览小部件,应用程序剪辑和Swift软件包中的内容。为了在设备上进行更无缝的实时预览,Xcode安装了适用于iOS 14和iPadOS 14的新Xcode Previews应用。(56388008) 新协议使您能够在Xcode的库中显示视图和修饰符。(56423420)LibraryContentProvider 代码补全具有新的,重点突出的用户界面,使查找补全更加容易。Xcode
  • Read plist in swift 3 playground
    I have followed loads of questions here but nothing seems to work. I am using Swift3 in a Playground. Running on El Capitan and Xcode 8.1. I have a plist with the root as a Dictionary containing one Int value and two 2D Arrays of Ints. plist Every question I follow does not seem to work the closest I have got is for the playground to not return errors but it seems to be constantly running (the spinning icon never stops). my current code, I believe to be the closest I have achieved. import Foundation if let path = Bundle.main.path(forResource: "levelList", ofType: "plist") { let plistXML =
  • Swift 4 JSON String with unknown UTF8 "�" character is not convertible to Data/ Dictionary
    Edit: I was able to pin down the issue to a MUCH more concentrated field. Although this post here isn't necessarily wrong with its assumptions, Swift 4 base64 String to Data not working due to special character is much more clear and has a Playground example. I have a string that has to be be serialized into a Dictionary in Swift 4. The app lets users upload data (JSON serialized as Data) and download it later. For the latter, the app does the following with the downloaded data (dlData) if let rootDict = NSKeyedUnarchiver.unarchiveObject(with: dlData) as? Dictionary<String, Any> { if let
  • 带有未知 UTF8“ ”字符的 Swift 4 JSON 字符串无法转换为数据/字典(Swift 4 JSON String with unknown UTF8 "�" character is not convertible to Data/ Dictionary)
    问题 编辑:我能够将问题确定为一个更集中的领域。 尽管这里的这篇文章的假设不一定是错误的,但 Swift 4 base64 String to Data 由于特殊字符而无法工作更加清晰,并且有一个 Playground 示例。 我有一个字符串,必须在 Swift 4 中序列化为字典。该应用程序允许用户上传数据(JSON 序列化为数据)并稍后下载。 对于后者,应用程序使用下载的数据 (dlData) 执行以下操作 if let rootDict = NSKeyedUnarchiver.unarchiveObject(with: dlData) as? Dictionary<String, Any> { if let content = rootDict["C"] as? String { if let data = content.data(using: .utf8, allowLossyConversion: true){ let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] ... } else { print("DATA DIDNT WORK") //gets printed with his data } 几乎每次都运行良好
  • 在 swift 3 playground 中阅读 plist(Read plist in swift 3 playground)
    问题 我在这里关注了很多问题,但似乎没有任何效果。 我在Playground使用Swift3 。 在 El Capitan 和 Xcode 8.1 上运行。 我有一个plist ,其根是一个包含一个 Int 值和两个 Int 二维数组的Dictionary 。 列表 我所关注的每个问题似乎都不起作用,最接近的是操场不返回错误,但它似乎一直在运行(旋转图标永远不会停止)。 我目前的代码,我相信是我已经实现的最接近的代码。 import Foundation if let path = Bundle.main.path(forResource: "levelList", ofType: "plist") { let plistXML = FileManager.default.contents(atPath: path)! let mydata = try! PropertyListSerialization.propertyList(from: plistXML, options: [], format: nil) as! [String:Any] } 我在类似上下文中从以前的堆栈溢出答案中尝试过的其他选项。 let mydata = Dictionary(fromPropertyList: path, format: "XML") as! [String: Any] ******
  • 在 Swift 中使用 Set 时出现编译器分段错误(Compiler segmentation fault while using Set in Swift)
    问题 这段代码工作正常: let lines = ["one", "one", "two"] let lineSet = lines 但是在编译这个的时候: let lines = ["one", "one", "two"] let lineSet = Set(lines) 我越来越: 由于信号导致命令失败:分段错误:11 我有 Xcode 版本 9.0 (9A235)。 这真的是一个错误还是我做错了什么? 我现在的解决方法: var lineSet = Set<String>() let lines = ["one", "one", "two"] lines.forEach { lineSet.insert($0) } 回答1 构建lineSet更好、更惯用的方法很简单: let lineSet: Set = ["one", "one", "two"] 希望这可以修复您的编译器崩溃。 不幸的是,我无法完全重现您的原始问题,因此我无法确定我的修复是否会有任何不同;) 如前所述,删除您的DerivedData文件夹是一个好主意( ~/Library/Caches/com.apple.dt.Xcode也可能有所帮助)。 当 Xcode 开始出现异常行为时,这是一种有点标准的做法。 回答2 从这里引用约翰卡斯威尔 编译器段错误始终是一个错误 根据我的经验,Playgrounds 有点问题
  • 游乐场导入:没有这样的模块“ Foo”(Playground Import: No Such Module 'Foo')
    问题 我一直遵循Apple的指示将自定义模块导入操场,包括此处的指示。 但是我得到了: 游乐场执行失败:/var/folders/z3/kd0nj4ln1rgcpm8bdz7067wh0000gs/T/./lldb/1874/playground1.swift:7:8:错误:无此类模块'Foo'导入Foo 如何恢复到Playground的正常导入状态? [编辑:注意,有两个答案已经给出了将游乐场与框架相关联的详细说明; 我遵循了这些指示,但是没有运气。 该解决方案将需要重新配置Xcode中的某些内容。 我的安装显然已损坏] 错误和尝试的详细图片: 这是基于@EricD的答案的另一种尝试,显示了目录结构,没有骰子。 回答1 对于上述解决方案均不起作用的那些解决方案(并且Xcode构建路径设置已设置为Unique ),我找到了一个解决方案。 该框架必须使用iOS模拟器设备(列表中的任何设备)而不是Generic iOS Device的方案构建,因为Playgrounds不支持该方案。 这个为我工作: 回答2 这是我使用Xcode 7.1进行OS X的方法: 创建新项目:OS X Cocoa Framework,Swift。 在此示例中,我将其命名为“ TestPlaygroundFMK”。 创建一个新的Swift文件。 在文件中添加一个类。 该代码必须是公开的。 我为我们的示例做了这个
  • 如果不应该,则可选绑定成功(Optional binding succeeds if it shouldn't)
    问题 这是我在Swift(略作修改)中发布的遍历视图控制器层次结构的可能解决方案: extension UIViewController { func traverseAndFindClass<T where T : UIViewController>(T.Type) -> T? { var currentVC = self while let parentVC = currentVC.parentViewController { println("comparing \(parentVC) to \(T.description())") if let result = parentVC as? T { // (XXX) return result } currentVC = parentVC } return nil } } 该方法应遍历父视图控制器层次结构,并返回给定类的第一个实例;如果未找到,则返回nil。 但这是行不通的,我也不知道为什么。 标记为(XXX)的可选绑定始终成功,因此即使不是T的实例,也将返回第一个父视图控制器。 这可以很容易地重现:从Xcode 6 GM中的“ iOS Master-Detail Application”模板创建一个项目,并将以下代码添加到MasterViewController类的viewDidLoad()中: if let vc =
  • 在Swift中解析JSON,AnyObject类型(Parse json in Swift, AnyObject type)
    问题 我正在尝试解析json,但是我在数据类型上遇到了一些困难,尤其是AnyObject类型+向下转换。 让我们考虑以下json(它是完整json的一部分)。 { "weather": [ { "id":804, "main":"Clouds", "description":"overcast clouds", "icon":"04d" } ], } 对我来说,json可以描述如下: - json: Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3) - "weather": Array of type [AnyObject] (or NSArray) - Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3) 我的json是AnyObject类型! (我使用JSONObjectWithData从URL获取JSON)。 然后,我想访问天气词典。 这是我写的代码。 var localError: NSError? var json: AnyObject! = NSJSONSerialization
  • SourceKitService已终止(SourceKitService Terminated)
    问题 我在Xcode上遇到问题,错误“ Source Kit Service Terminated”弹出,并且所有语法突出显示和代码完成在Swift中都消失了。 我怎样才能解决这个问题? 这是一个示例图像: 回答1 我的答案(Xcode6-Beta7)只是删除Derived Data文件夹。 Preferences > Locations > Derived Data > click the arrow to open in Finder > trash it. 希望这对某人有帮助。 显然有很多原因可以导致此崩溃。 回答2 我相信我可能已经找到了更通用的解决方案。 下面是我用来鼓励Xcode不产生SourceKitService Terminated错误的步骤。 我出现的症状: 当我启动一个新的游乐场时,我将收到一个关于无法与游乐场进行通信的Error running playground: Failed prepare for communication with playground. ( Error running playground: Failed prepare for communication with playground.请参见Twitter上的此图像。 当我将游乐场从OS X切换到iOS ,我会收到另一个错误(不幸的是我没有写下那个错误)。
  • 在 swift4.1 中将 Any 转换为 Float 总是失败(Cast Any to Float always fails in swift4.1)
    问题 在前一个版本中,要从[String: Any]字典中获取浮点值,我可以使用let float = dict["somekey"] as? Float let float = dict["somekey"] as? Float ,但在 swift4.1 中,它不起作用。 在我得到它之前,似乎dict["somekey"]的类型已经被隐式推断为Double ,所以从Double到Float总是失败。 我想知道这是一个新特性还是只是一个错误。 --这里是更新。 我重新下载了一个 Xcode9.2 并做了一些实验,现在我想我知道发生了什么。 下面是测试代码: let dict: [String : Any] = ["key": 0.1] if let float: Float = dict["key"] as? Float { print(float) } else { print("nil") } let dict1: [String : Any] = ["key": NSNumber(value: 0.2)] if let float: Float = dict1["key"] as? Float { print(float) } else { print("nil") } let number = NSNumber(value: 0.3) if let float: Float
  • Parse json in Swift, AnyObject type
    I'm trying to parse a json but I have some difficulties with the data types and notably the AnyObject type + downcasting. Let's consider the following json (it's an extract of a full json). { "weather": [ { "id":804, "main":"Clouds", "description":"overcast clouds", "icon":"04d" } ], } To me, the json can be described as follow : - json: Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3) - "weather": Array of type [AnyObject] (or NSArray) - Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3) My json
  • 如何从您自己的项目中将自己的类导入Playground(How to import own classes from your own project into a Playground)
    问题 假设这样的设置: 您有一个Xcode 6项目,在这里您已经用Objective-C和Swift实现了自己的类(例如MyView和MyViewController) 您已经在项目中添加了Playground 在Playground中,可以使用import关键字import类似UIKit模块(框架)。 您如何从Playground启用对项目其他班级的访问? 尝试直接访问项目类会直接导致错误消息:使用未解析的标识符'MyView' 回答1 从Xcode 6.0 Beta 5开始,现在可以将自己的框架导入操场。 这提供了一种在应用程序和Playground之间共享代码的方法,可以同时导入您的框架。 去做这个: 您的游乐场必须与生成框架的项目位于同一工作空间中。 您的工作区必须包含生成框架的目标,而不是使用预先构建的框架。 您必须已经构建了框架。 如果它是iOS框架,则必须为64位运行目标(例如iPhone 5s)构建,并且必须为模拟器构建。 您必须具有一个主动方案,该方案可以构建至少一个目标(该目标的构建位置将在游乐场的框架搜索路径中使用)。 您的“构建位置”首选项(在Xcode的高级“位置”设置中)不应设置为“旧版”。 如果您的框架不是Swift框架,则“ Defines Module”构建设置必须设置为“ Yes”。 您必须在框架的操场上添加导入语句。 一旦满足所有这些条件
  • Xcode 挂在“编译 Swift 源文件”上(Xcode hangs on “Compiling Swift source files”)
    问题 我正在运行 Xcode 7.3.1。 在构建我的基于 Swift 的项目时,它挂在“编译 Swift 源文件”上。 我尝试了删除DerivedData 、清理、运行、重新启动 Xcode、重新启动 OS X 的各种组合,但似乎都不起作用。 有任何想法吗? 回答1 我做了一个类扩展自己。 这也会导致 Swift 编译器卡在一个循环中而不会出错: class X: X 回答2 感谢所有评论者的建议。 我将其缩小到map的闭包引用我已删除的属性。 例子: var people: [Person] = ... let foo = people.map { "\($0.name), \($0.age)" } Person看起来像: protocol Person { var name: String { get } var age: Int { get } } 这一切正常。 然后我删除了age同时保持闭包不变。 这导致 Xcode 变得无可救药地困惑。 可能与 Swift 的类型推断有关。 回答3 将 Build Settings 中的“Swift Compiler Optimization Level”从“Whole module optimization”更改为“Single file optimization”。 这可能不是你的问题,但它解决了我被困半天的问题。 这可能只是最近
  • Swift 编译器挂起! 这是一个错误吗?(Swift compiler hangs! Is it a bug?)
    问题 有一次,当我在处理 Swift 项目时,Xcode 卡在状态栏中的“正在编译 Swift 源代码”消息中。 不管我等了多久,编译都没有完成。 我回滚了我最近的更改,很快意识到混淆编译器的是一个非常简单的枚举结构。 下面是一个说明问题的 Playground 示例。 创建一个新的 Playground 并粘贴此代码。 你看到任何输出了吗? // Playground - noun: a place where people can play import UIKit enum FastingType: Int { case NoFast=0, Vegetarian, FishAllowed, FastFree, Cheesefare } class Fasting { var allowedFood = [ .NoFast: ["meat", "fish", "milk", "egg", "cupcake"], .Vegetarian: ["vegetables", "bread", "nuts"], .FishAllowed: ["fish", "vegetables", "bread", "nuts"], .FastFree: ["cupcake", "meat", "fish", "cheese"], .Cheesefare: ["cheese", "cupcake",
  • Swift 4.2, String firstIndex() function error in Xcode playground
    I was reading "The Swift Programming Language Swift 4.2" and in "Strings and Characters" chapter under "Substrings" section, the following code is given as an example: let greeting = "Hello, world!" let index = greeting.firstIndex(of: ",") ?? greeting.endIndex let beginning = greeting[..<index] // beginning is "Hello" // Convert the result to a String for long-term storage. let newString = String(beginning) I copied and pasted this chunk into my Xcode playground; however, I got the following error: Playground execution failed: error: MyPlayground.playground:6:13: error: value of type 'String'
  • Swift compiler hangs! Is it a bug?
    At one point, while I was working on a Swift project, the Xcode got stuck with "Compiling Swift source" message in the status bar. The compilation did not finish no matter how long I waited. I rolled back my recent changes, and soon realized that what confuses the compiler is a very simple enum construct. Below is a Playground example that illustrates the problem. Create a new Playground and paste this code. Do you see any output? // Playground - noun: a place where people can play import UIKit enum FastingType: Int { case NoFast=0, Vegetarian, FishAllowed, FastFree, Cheesefare } class Fasting
  • Cast Any to Float always fails in swift4.1
    In the former version, to get a float value from a [String: Any] dictionary, I can use let float = dict["somekey"] as? Float, but in swift4.1, it doesn't work. It seems the type of dict["somekey"] has been implicitly inferred as Double before I get it, so casting from Double to Float always fails. I wonder if it is a new characteristic or just a bug. --Here is the update. I re-downloadeded an Xcode9.2 and did some experiments, now I think I figure out what's going on. Here is the test code: let dict: [String : Any] = ["key": 0.1] if let float: Float = dict["key"] as? Float { print(float) }
  • Xcode playground gets stuck on 'Running playground' or 'Launching simulator' and won't run the code, what to do?
    Every time I create a new playground in order to test some code, Xcode gets stuck and won't run the code. It simply presents 'Running playground' or 'Launching simulator' statement at the top of the screen with the loading icon promisingly spinning next to it but nothing happens. Sometimes this continues indefinitely and sometimes Xcode halts and prints this to console : Playground execution failed: error: Couldn't lookup symbols: __swift_FORCE_LOAD_$_swiftCoreImage __swift_FORCE_LOAD_$_swiftFoundation _playground_log_hidden _playground_logger_initialize _playground_log_postprint thread #1