[swift-evolution] : [Proposal] Change UnicodeScalar initializer to failable
Duan
daniel at duan.org
Thu Jul 21 11:39:16 CDT 2016
+1
"Explicit is better than implicit"
Daniel Duan
Sent from my iPhone
> On Jul 21, 2016, at 9:34 AM, Björn Forster via swift-evolution <swift-evolution at swift.org> wrote:
>
> +1
>
> I think this helps making Swift code more robust and should be included in Swift 3.
>
> The scenario described by Xin is a real world and not an academic one.
>
> Also, the change he proposes is a very small one, so you get "much bang for the bucks" in my point of view.
>
> Björn
>
> Am Dienstag, 19. Juli 2016 schrieb Xin Tong via swift-evolution :
>> Hi,
>> I would like to propose changing unicodescalar initializer to failable.
>> Currently, when you pass an invalid value to the UnicodeScalar initializer the swift stdlib crashes the program by calling _precondition. This is bad if you construct a unicode scalar from unknown input.
>> As a result. I would like to propose to mark the initializer as failable and return nil in case of a failure.
>>
>> Currently, in the code below, the stdlib crashes the program by calling _precondition if codepoint is not a valid unicode.
>> var string = “"
>> let codepoint: UInt32 = 55357 // this is invalid
>> let ucode = UnicodeScalar(codepoint) // Program crashes at this point.
>> string.append(code)
>>
>> After marking the initializer as failable, users can write code like this. And the program will execute fine even codepoint is invalid.
>> var string = "" let codepoint: UInt32 = 55357 // this is invalid
>> let ucode = UnicodeScalar(codepoint)
>> if ucode != nil {
>> string.append(code!)
>> } else {
>> // do something else
>> }
>>
>> As the initializer is now failable, it returns an optional, so optional unchaining or forced unwrapping needs to be used. Alternatively, its also possible to leave status quo and force the users to do input checks
>> before trying to construct a UnicodeScalar. But i feel having failable initializer helps user to write more robust code.
>> -Xin
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160721/651db70c/attachment.html>
More information about the swift-evolution
mailing list