5

I have a function that requires a unichar parameter. But could not find a nice way to initialize a unichar in swift.

I am using the following way:

var delimitedBy:unichar = ("," as NSString).characterAtIndex(0)

Is there a better way to initialize a unichar in swift?

turkenh
  • 2,564
  • 3
  • 25
  • 32

3 Answers3

6

Swift can infer the type and you don't need to cast the String literal to NSString:

var delimitedBy = ",".characterAtIndex(0)
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • 1
    Doesn't work in Xcode 7.1.1: `error: value of type 'String' has no member 'characterAtindex' let dog = "a".characterAtindex(0)` – 7stud Jan 05 '16 at 13:59
  • 2
    @7stud, you have a typo. Note that the `I` is capitalized in `characterAtIndex`. – vacawama Jan 05 '16 at 14:15
4

Another possible solution:

var delimitedBy = first(",".utf16)!

(Note that unichar is a type alias for UInt16). This works also with string variables (which of course should not be the empty string).


Update for Swift 2/Xcode 7:

var delimitedBy = ",".utf16.first!
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Doesn't work in Xcode 7.1.1: `note: 'first' has been explicitly marked unavailable here public func first(x: C) -> C.Generator.Element?` – 7stud Jan 05 '16 at 14:00
  • @7stud: Thanks for letting me know! – Martin R Jan 05 '16 at 14:08
  • @7stud: If you command-click on "first" in Xcode then you'll see that it is a protocol extension method of CollectionType. Then you can find it here: https://developer.apple.com/library/ios//documentation/Swift/Reference/Swift_CollectionType_Protocol/index.html#//apple_ref/swift/intfp/CollectionType/s:vPSs14CollectionType5firstGSqqqq_S_9GeneratorSs13GeneratorType7Element_. – Martin R Jan 05 '16 at 16:19
  • Thanks. I'm having trouble negotiating the docs. I can't even find `.utf16`. I found that one with option+click.. – 7stud Jan 05 '16 at 16:24
0

Swift 5 would be:

let delimeter = ",".utf16.first!
Leonid Silver
  • 384
  • 4
  • 8