[swift-users] Swift 4 Strings and flatMap

Ole Begemann ole at oleb.net
Sat Oct 21 11:39:03 CDT 2017


On 21.10.17 02:50, Santiago Gil via swift-users wrote:
> I just ran into a bug after a Swift 4 migration where we expected 
> [String] and got [Character] from a flatMap since flatMap will flatten 
> the String since it's now a collection.  While I understand why 
> flatMap behaves this way now that string are collections, in testing 
> this I found some weird behaviour...
>
> var strArr = ["Hi", "hello"]
>
> let result = strArr.flatMap { x in
>
> returnx
>
> }
>
>
> The type of results ends up being [Character] in the above case. 
> However, adding a print statement changes things.
>
> var strArr = ["Hi", "hello"]
>
> let result = strArr.flatMap { x in
>
> print(x)
>
> return x
>
> }
>
> In this case, result is of type [String]
>
> This seems like a bug, or is this expected Swift behaviour?
>

It looks like the compiler infers the type of the closure in the second 
example to be (String) -> Optional<String> instead of String -> String.

I don't know why and I definitely find it surprising.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171021/3d9a6fb1/attachment.html>


More information about the swift-users mailing list