[swift-evolution] : [Proposal] Change UnicodeScalar initializer to failable

Xin Tong xin_tong at apple.com
Tue Jul 19 12:14:33 CDT 2016


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  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160719/6562eea2/attachment.html>


More information about the swift-evolution mailing list