What's the simplest way to convert from a single character String to an ASCII value in Swift?












48














I just want to get the ASCII value of a single char string in Swift. This is how I'm currently doing it:



var singleChar = "a"
println(singleChar.unicodeScalars[singleChar.unicodeScalars.startIndex].value) //prints: 97


This is so ugly though. There must be a simpler way.










share|improve this question





























    48














    I just want to get the ASCII value of a single char string in Swift. This is how I'm currently doing it:



    var singleChar = "a"
    println(singleChar.unicodeScalars[singleChar.unicodeScalars.startIndex].value) //prints: 97


    This is so ugly though. There must be a simpler way.










    share|improve this question



























      48












      48








      48


      13





      I just want to get the ASCII value of a single char string in Swift. This is how I'm currently doing it:



      var singleChar = "a"
      println(singleChar.unicodeScalars[singleChar.unicodeScalars.startIndex].value) //prints: 97


      This is so ugly though. There must be a simpler way.










      share|improve this question















      I just want to get the ASCII value of a single char string in Swift. This is how I'm currently doing it:



      var singleChar = "a"
      println(singleChar.unicodeScalars[singleChar.unicodeScalars.startIndex].value) //prints: 97


      This is so ugly though. There must be a simpler way.







      string swift ascii






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 16 '15 at 15:37







      user5385823

















      asked Apr 23 '15 at 22:10









      DavidNorman

      1,12811420




      1,12811420
























          13 Answers
          13






          active

          oldest

          votes


















          73














          You can create an extension:



          Swift 4 or later



          extension Character {
          var isAscii: Bool {
          return unicodeScalars.first?.isASCII == true
          }
          var ascii: UInt32? {
          return isAscii ? unicodeScalars.first?.value : nil
          }
          }




          extension StringProtocol {
          var ascii: [UInt32] {
          return compactMap { $0.ascii }
          }
          }




          Character("a").isAscii  // true
          Character("a").ascii // 97

          Character("á").isAscii // false
          Character("á").ascii // nil

          "abc".ascii // [97, 98, 99]
          "abc".ascii[0] // 97
          "abc".ascii[1] // 98
          "abc".ascii[2] // 99





          share|improve this answer































            10














            You can use NSString's characterAtIndex to accomplish this...



            var singleCharString = "a" as NSString
            var singleCharValue = singleCharString.characterAtIndex(0)
            println("The value of (singleCharString) is (singleCharValue)") // The value of a is 97





            share|improve this answer























            • "a".characterAtIndex(0) works.
              – vacawama
              Apr 24 '15 at 0:55






            • 1




              @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
              – Kamaldeep singh Bhatia
              Apr 30 '18 at 14:15



















            10














            UnicodeScalar("1")!.value // returns 49


            Swift 3.1






            share|improve this answer





























              9














              Now in Xcode 7.1 and Swift 2.1



              var singleChar = "a"

              singleChar.unicodeScalars.first?.value





              share|improve this answer































                3














                Here's my implementation, it returns an array of the ASCII values.



                extension String {

                func asciiValueOfString() -> [UInt32] {

                var retVal = [UInt32]()
                for val in self.unicodeScalars where val.isASCII() {
                retVal.append(UInt32(val))
                }
                return retVal
                }
                }


                Note: Yes it's Swift 2 compatible.






                share|improve this answer





























                  2














                  The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:



                  var x : UInt32 = 0
                  let char = "a"
                  for sc in char.unicodeScalars {x = sc.value; break}


                  You can actually omit the break in this case, of course, since there is only one unicode scalar.



                  Or, convert to an Array and use Int indexing (the last resort of the desperate):



                  let char = "a"
                  let x = Array(char.unicodeScalars)[0].value





                  share|improve this answer





























                    2














                    A slightly shorter way of doing this could be:



                    first(singleChar.unicodeScalars)!.value


                    As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:



                    if let ascii = first(singleChar.unicodeScalars)?.value {

                    }


                    Or, if you want to be extra-paranoid,



                    if let char = first(singleChar.unicodeScalars) where char.isASCII() {
                    let ascii = char.value
                    }





                    share|improve this answer





























                      1














                      var singchar = "a" as NSString

                      print(singchar.character(at: 0))


                      Swift 3.1






                      share|improve this answer





























                        1














                        Swift 4.1



                        https://oleb.net/blog/2017/11/swift-4-strings/



                        let flags = "99_problems"
                        flags.unicodeScalars.map {
                        "(String($0.value, radix: 16, uppercase: true))"
                        }


                        Result:



                        ["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]






                        share|improve this answer





























                          1














                          Swift 4.2



                          The easiest way to get ASCII values from a Swift string is below



                          let str = "Swift string"
                          for ascii in str.utf8 {
                          print(ascii)
                          }


                          Output:



                          83
                          119
                          105
                          102
                          116
                          32
                          115
                          116
                          114
                          105
                          110
                          103





                          share|improve this answer





















                          • Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                            – Leo Dabus
                            Jul 17 '18 at 0:44





















                          0














                          Swift 4



                          print("c".utf8["c".utf8.startIndex])


                          or



                          let cu = "c".utf8
                          print(cu[cu.startIndex])


                          Both print 99. Works for any ASCII character.






                          share|improve this answer





























                            0














                            There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.



                            var singleChar = "a"
                            UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])





                            share|improve this answer





















                            • Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                              – Leo Dabus
                              Jul 17 '18 at 0:08





















                            0














                            Swift 4+



                            Char to ASCII



                            let charVal = String(ch).unicodeScalars
                            var asciiVal = charVal[charVal.startIndex].value


                            ASCII to Char



                            let char = Character(UnicodeScalar(asciiVal)!)





                            share|improve this answer





















                              Your Answer






                              StackExchange.ifUsing("editor", function () {
                              StackExchange.using("externalEditor", function () {
                              StackExchange.using("snippets", function () {
                              StackExchange.snippets.init();
                              });
                              });
                              }, "code-snippets");

                              StackExchange.ready(function() {
                              var channelOptions = {
                              tags: "".split(" "),
                              id: "1"
                              };
                              initTagRenderer("".split(" "), "".split(" "), channelOptions);

                              StackExchange.using("externalEditor", function() {
                              // Have to fire editor after snippets, if snippets enabled
                              if (StackExchange.settings.snippets.snippetsEnabled) {
                              StackExchange.using("snippets", function() {
                              createEditor();
                              });
                              }
                              else {
                              createEditor();
                              }
                              });

                              function createEditor() {
                              StackExchange.prepareEditor({
                              heartbeatType: 'answer',
                              autoActivateHeartbeat: false,
                              convertImagesToLinks: true,
                              noModals: true,
                              showLowRepImageUploadWarning: true,
                              reputationToPostImages: 10,
                              bindNavPrevention: true,
                              postfix: "",
                              imageUploader: {
                              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                              allowUrls: true
                              },
                              onDemand: true,
                              discardSelector: ".discard-answer"
                              ,immediatelyShowMarkdownHelp:true
                              });


                              }
                              });














                              draft saved

                              draft discarded


















                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29835242%2fwhats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown

























                              13 Answers
                              13






                              active

                              oldest

                              votes








                              13 Answers
                              13






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes









                              73














                              You can create an extension:



                              Swift 4 or later



                              extension Character {
                              var isAscii: Bool {
                              return unicodeScalars.first?.isASCII == true
                              }
                              var ascii: UInt32? {
                              return isAscii ? unicodeScalars.first?.value : nil
                              }
                              }




                              extension StringProtocol {
                              var ascii: [UInt32] {
                              return compactMap { $0.ascii }
                              }
                              }




                              Character("a").isAscii  // true
                              Character("a").ascii // 97

                              Character("á").isAscii // false
                              Character("á").ascii // nil

                              "abc".ascii // [97, 98, 99]
                              "abc".ascii[0] // 97
                              "abc".ascii[1] // 98
                              "abc".ascii[2] // 99





                              share|improve this answer




























                                73














                                You can create an extension:



                                Swift 4 or later



                                extension Character {
                                var isAscii: Bool {
                                return unicodeScalars.first?.isASCII == true
                                }
                                var ascii: UInt32? {
                                return isAscii ? unicodeScalars.first?.value : nil
                                }
                                }




                                extension StringProtocol {
                                var ascii: [UInt32] {
                                return compactMap { $0.ascii }
                                }
                                }




                                Character("a").isAscii  // true
                                Character("a").ascii // 97

                                Character("á").isAscii // false
                                Character("á").ascii // nil

                                "abc".ascii // [97, 98, 99]
                                "abc".ascii[0] // 97
                                "abc".ascii[1] // 98
                                "abc".ascii[2] // 99





                                share|improve this answer


























                                  73












                                  73








                                  73






                                  You can create an extension:



                                  Swift 4 or later



                                  extension Character {
                                  var isAscii: Bool {
                                  return unicodeScalars.first?.isASCII == true
                                  }
                                  var ascii: UInt32? {
                                  return isAscii ? unicodeScalars.first?.value : nil
                                  }
                                  }




                                  extension StringProtocol {
                                  var ascii: [UInt32] {
                                  return compactMap { $0.ascii }
                                  }
                                  }




                                  Character("a").isAscii  // true
                                  Character("a").ascii // 97

                                  Character("á").isAscii // false
                                  Character("á").ascii // nil

                                  "abc".ascii // [97, 98, 99]
                                  "abc".ascii[0] // 97
                                  "abc".ascii[1] // 98
                                  "abc".ascii[2] // 99





                                  share|improve this answer














                                  You can create an extension:



                                  Swift 4 or later



                                  extension Character {
                                  var isAscii: Bool {
                                  return unicodeScalars.first?.isASCII == true
                                  }
                                  var ascii: UInt32? {
                                  return isAscii ? unicodeScalars.first?.value : nil
                                  }
                                  }




                                  extension StringProtocol {
                                  var ascii: [UInt32] {
                                  return compactMap { $0.ascii }
                                  }
                                  }




                                  Character("a").isAscii  // true
                                  Character("a").ascii // 97

                                  Character("á").isAscii // false
                                  Character("á").ascii // nil

                                  "abc".ascii // [97, 98, 99]
                                  "abc".ascii[0] // 97
                                  "abc".ascii[1] // 98
                                  "abc".ascii[2] // 99






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 21 '18 at 11:24

























                                  answered Apr 23 '15 at 22:59









                                  Leo Dabus

                                  130k30264340




                                  130k30264340

























                                      10














                                      You can use NSString's characterAtIndex to accomplish this...



                                      var singleCharString = "a" as NSString
                                      var singleCharValue = singleCharString.characterAtIndex(0)
                                      println("The value of (singleCharString) is (singleCharValue)") // The value of a is 97





                                      share|improve this answer























                                      • "a".characterAtIndex(0) works.
                                        – vacawama
                                        Apr 24 '15 at 0:55






                                      • 1




                                        @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                        – Kamaldeep singh Bhatia
                                        Apr 30 '18 at 14:15
















                                      10














                                      You can use NSString's characterAtIndex to accomplish this...



                                      var singleCharString = "a" as NSString
                                      var singleCharValue = singleCharString.characterAtIndex(0)
                                      println("The value of (singleCharString) is (singleCharValue)") // The value of a is 97





                                      share|improve this answer























                                      • "a".characterAtIndex(0) works.
                                        – vacawama
                                        Apr 24 '15 at 0:55






                                      • 1




                                        @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                        – Kamaldeep singh Bhatia
                                        Apr 30 '18 at 14:15














                                      10












                                      10








                                      10






                                      You can use NSString's characterAtIndex to accomplish this...



                                      var singleCharString = "a" as NSString
                                      var singleCharValue = singleCharString.characterAtIndex(0)
                                      println("The value of (singleCharString) is (singleCharValue)") // The value of a is 97





                                      share|improve this answer














                                      You can use NSString's characterAtIndex to accomplish this...



                                      var singleCharString = "a" as NSString
                                      var singleCharValue = singleCharString.characterAtIndex(0)
                                      println("The value of (singleCharString) is (singleCharValue)") // The value of a is 97






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Apr 23 '15 at 23:34

























                                      answered Apr 23 '15 at 22:16









                                      timgcarlson

                                      2,2431644




                                      2,2431644












                                      • "a".characterAtIndex(0) works.
                                        – vacawama
                                        Apr 24 '15 at 0:55






                                      • 1




                                        @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                        – Kamaldeep singh Bhatia
                                        Apr 30 '18 at 14:15


















                                      • "a".characterAtIndex(0) works.
                                        – vacawama
                                        Apr 24 '15 at 0:55






                                      • 1




                                        @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                        – Kamaldeep singh Bhatia
                                        Apr 30 '18 at 14:15
















                                      "a".characterAtIndex(0) works.
                                      – vacawama
                                      Apr 24 '15 at 0:55




                                      "a".characterAtIndex(0) works.
                                      – vacawama
                                      Apr 24 '15 at 0:55




                                      1




                                      1




                                      @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                      – Kamaldeep singh Bhatia
                                      Apr 30 '18 at 14:15




                                      @vacawama Swift 4, I am getting error error: value of type 'String' has no member 'character'. but when using "a" as NSString its working :)
                                      – Kamaldeep singh Bhatia
                                      Apr 30 '18 at 14:15











                                      10














                                      UnicodeScalar("1")!.value // returns 49


                                      Swift 3.1






                                      share|improve this answer


























                                        10














                                        UnicodeScalar("1")!.value // returns 49


                                        Swift 3.1






                                        share|improve this answer
























                                          10












                                          10








                                          10






                                          UnicodeScalar("1")!.value // returns 49


                                          Swift 3.1






                                          share|improve this answer












                                          UnicodeScalar("1")!.value // returns 49


                                          Swift 3.1







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jun 11 '17 at 6:12









                                          Joe

                                          12115




                                          12115























                                              9














                                              Now in Xcode 7.1 and Swift 2.1



                                              var singleChar = "a"

                                              singleChar.unicodeScalars.first?.value





                                              share|improve this answer




























                                                9














                                                Now in Xcode 7.1 and Swift 2.1



                                                var singleChar = "a"

                                                singleChar.unicodeScalars.first?.value





                                                share|improve this answer


























                                                  9












                                                  9








                                                  9






                                                  Now in Xcode 7.1 and Swift 2.1



                                                  var singleChar = "a"

                                                  singleChar.unicodeScalars.first?.value





                                                  share|improve this answer














                                                  Now in Xcode 7.1 and Swift 2.1



                                                  var singleChar = "a"

                                                  singleChar.unicodeScalars.first?.value






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Dec 18 '15 at 0:52

























                                                  answered Dec 17 '15 at 23:34









                                                  wakeupsumo

                                                  18614




                                                  18614























                                                      3














                                                      Here's my implementation, it returns an array of the ASCII values.



                                                      extension String {

                                                      func asciiValueOfString() -> [UInt32] {

                                                      var retVal = [UInt32]()
                                                      for val in self.unicodeScalars where val.isASCII() {
                                                      retVal.append(UInt32(val))
                                                      }
                                                      return retVal
                                                      }
                                                      }


                                                      Note: Yes it's Swift 2 compatible.






                                                      share|improve this answer


























                                                        3














                                                        Here's my implementation, it returns an array of the ASCII values.



                                                        extension String {

                                                        func asciiValueOfString() -> [UInt32] {

                                                        var retVal = [UInt32]()
                                                        for val in self.unicodeScalars where val.isASCII() {
                                                        retVal.append(UInt32(val))
                                                        }
                                                        return retVal
                                                        }
                                                        }


                                                        Note: Yes it's Swift 2 compatible.






                                                        share|improve this answer
























                                                          3












                                                          3








                                                          3






                                                          Here's my implementation, it returns an array of the ASCII values.



                                                          extension String {

                                                          func asciiValueOfString() -> [UInt32] {

                                                          var retVal = [UInt32]()
                                                          for val in self.unicodeScalars where val.isASCII() {
                                                          retVal.append(UInt32(val))
                                                          }
                                                          return retVal
                                                          }
                                                          }


                                                          Note: Yes it's Swift 2 compatible.






                                                          share|improve this answer












                                                          Here's my implementation, it returns an array of the ASCII values.



                                                          extension String {

                                                          func asciiValueOfString() -> [UInt32] {

                                                          var retVal = [UInt32]()
                                                          for val in self.unicodeScalars where val.isASCII() {
                                                          retVal.append(UInt32(val))
                                                          }
                                                          return retVal
                                                          }
                                                          }


                                                          Note: Yes it's Swift 2 compatible.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Oct 6 '15 at 17:43









                                                          Sakiboy

                                                          3,76513250




                                                          3,76513250























                                                              2














                                                              The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:



                                                              var x : UInt32 = 0
                                                              let char = "a"
                                                              for sc in char.unicodeScalars {x = sc.value; break}


                                                              You can actually omit the break in this case, of course, since there is only one unicode scalar.



                                                              Or, convert to an Array and use Int indexing (the last resort of the desperate):



                                                              let char = "a"
                                                              let x = Array(char.unicodeScalars)[0].value





                                                              share|improve this answer


























                                                                2














                                                                The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:



                                                                var x : UInt32 = 0
                                                                let char = "a"
                                                                for sc in char.unicodeScalars {x = sc.value; break}


                                                                You can actually omit the break in this case, of course, since there is only one unicode scalar.



                                                                Or, convert to an Array and use Int indexing (the last resort of the desperate):



                                                                let char = "a"
                                                                let x = Array(char.unicodeScalars)[0].value





                                                                share|improve this answer
























                                                                  2












                                                                  2








                                                                  2






                                                                  The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:



                                                                  var x : UInt32 = 0
                                                                  let char = "a"
                                                                  for sc in char.unicodeScalars {x = sc.value; break}


                                                                  You can actually omit the break in this case, of course, since there is only one unicode scalar.



                                                                  Or, convert to an Array and use Int indexing (the last resort of the desperate):



                                                                  let char = "a"
                                                                  let x = Array(char.unicodeScalars)[0].value





                                                                  share|improve this answer












                                                                  The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:



                                                                  var x : UInt32 = 0
                                                                  let char = "a"
                                                                  for sc in char.unicodeScalars {x = sc.value; break}


                                                                  You can actually omit the break in this case, of course, since there is only one unicode scalar.



                                                                  Or, convert to an Array and use Int indexing (the last resort of the desperate):



                                                                  let char = "a"
                                                                  let x = Array(char.unicodeScalars)[0].value






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Apr 23 '15 at 23:18









                                                                  matt

                                                                  324k45522722




                                                                  324k45522722























                                                                      2














                                                                      A slightly shorter way of doing this could be:



                                                                      first(singleChar.unicodeScalars)!.value


                                                                      As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:



                                                                      if let ascii = first(singleChar.unicodeScalars)?.value {

                                                                      }


                                                                      Or, if you want to be extra-paranoid,



                                                                      if let char = first(singleChar.unicodeScalars) where char.isASCII() {
                                                                      let ascii = char.value
                                                                      }





                                                                      share|improve this answer


























                                                                        2














                                                                        A slightly shorter way of doing this could be:



                                                                        first(singleChar.unicodeScalars)!.value


                                                                        As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:



                                                                        if let ascii = first(singleChar.unicodeScalars)?.value {

                                                                        }


                                                                        Or, if you want to be extra-paranoid,



                                                                        if let char = first(singleChar.unicodeScalars) where char.isASCII() {
                                                                        let ascii = char.value
                                                                        }





                                                                        share|improve this answer
























                                                                          2












                                                                          2








                                                                          2






                                                                          A slightly shorter way of doing this could be:



                                                                          first(singleChar.unicodeScalars)!.value


                                                                          As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:



                                                                          if let ascii = first(singleChar.unicodeScalars)?.value {

                                                                          }


                                                                          Or, if you want to be extra-paranoid,



                                                                          if let char = first(singleChar.unicodeScalars) where char.isASCII() {
                                                                          let ascii = char.value
                                                                          }





                                                                          share|improve this answer












                                                                          A slightly shorter way of doing this could be:



                                                                          first(singleChar.unicodeScalars)!.value


                                                                          As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:



                                                                          if let ascii = first(singleChar.unicodeScalars)?.value {

                                                                          }


                                                                          Or, if you want to be extra-paranoid,



                                                                          if let char = first(singleChar.unicodeScalars) where char.isASCII() {
                                                                          let ascii = char.value
                                                                          }






                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Apr 24 '15 at 1:00









                                                                          Airspeed Velocity

                                                                          34.4k684101




                                                                          34.4k684101























                                                                              1














                                                                              var singchar = "a" as NSString

                                                                              print(singchar.character(at: 0))


                                                                              Swift 3.1






                                                                              share|improve this answer


























                                                                                1














                                                                                var singchar = "a" as NSString

                                                                                print(singchar.character(at: 0))


                                                                                Swift 3.1






                                                                                share|improve this answer
























                                                                                  1












                                                                                  1








                                                                                  1






                                                                                  var singchar = "a" as NSString

                                                                                  print(singchar.character(at: 0))


                                                                                  Swift 3.1






                                                                                  share|improve this answer












                                                                                  var singchar = "a" as NSString

                                                                                  print(singchar.character(at: 0))


                                                                                  Swift 3.1







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Sep 19 '17 at 3:43









                                                                                  Shauket Sheikh

                                                                                  1,025821




                                                                                  1,025821























                                                                                      1














                                                                                      Swift 4.1



                                                                                      https://oleb.net/blog/2017/11/swift-4-strings/



                                                                                      let flags = "99_problems"
                                                                                      flags.unicodeScalars.map {
                                                                                      "(String($0.value, radix: 16, uppercase: true))"
                                                                                      }


                                                                                      Result:



                                                                                      ["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]






                                                                                      share|improve this answer


























                                                                                        1














                                                                                        Swift 4.1



                                                                                        https://oleb.net/blog/2017/11/swift-4-strings/



                                                                                        let flags = "99_problems"
                                                                                        flags.unicodeScalars.map {
                                                                                        "(String($0.value, radix: 16, uppercase: true))"
                                                                                        }


                                                                                        Result:



                                                                                        ["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]






                                                                                        share|improve this answer
























                                                                                          1












                                                                                          1








                                                                                          1






                                                                                          Swift 4.1



                                                                                          https://oleb.net/blog/2017/11/swift-4-strings/



                                                                                          let flags = "99_problems"
                                                                                          flags.unicodeScalars.map {
                                                                                          "(String($0.value, radix: 16, uppercase: true))"
                                                                                          }


                                                                                          Result:



                                                                                          ["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]






                                                                                          share|improve this answer












                                                                                          Swift 4.1



                                                                                          https://oleb.net/blog/2017/11/swift-4-strings/



                                                                                          let flags = "99_problems"
                                                                                          flags.unicodeScalars.map {
                                                                                          "(String($0.value, radix: 16, uppercase: true))"
                                                                                          }


                                                                                          Result:



                                                                                          ["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered May 1 '18 at 13:46









                                                                                          rustyMagnet

                                                                                          1,026620




                                                                                          1,026620























                                                                                              1














                                                                                              Swift 4.2



                                                                                              The easiest way to get ASCII values from a Swift string is below



                                                                                              let str = "Swift string"
                                                                                              for ascii in str.utf8 {
                                                                                              print(ascii)
                                                                                              }


                                                                                              Output:



                                                                                              83
                                                                                              119
                                                                                              105
                                                                                              102
                                                                                              116
                                                                                              32
                                                                                              115
                                                                                              116
                                                                                              114
                                                                                              105
                                                                                              110
                                                                                              103





                                                                                              share|improve this answer





















                                                                                              • Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                                – Leo Dabus
                                                                                                Jul 17 '18 at 0:44


















                                                                                              1














                                                                                              Swift 4.2



                                                                                              The easiest way to get ASCII values from a Swift string is below



                                                                                              let str = "Swift string"
                                                                                              for ascii in str.utf8 {
                                                                                              print(ascii)
                                                                                              }


                                                                                              Output:



                                                                                              83
                                                                                              119
                                                                                              105
                                                                                              102
                                                                                              116
                                                                                              32
                                                                                              115
                                                                                              116
                                                                                              114
                                                                                              105
                                                                                              110
                                                                                              103





                                                                                              share|improve this answer





















                                                                                              • Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                                – Leo Dabus
                                                                                                Jul 17 '18 at 0:44
















                                                                                              1












                                                                                              1








                                                                                              1






                                                                                              Swift 4.2



                                                                                              The easiest way to get ASCII values from a Swift string is below



                                                                                              let str = "Swift string"
                                                                                              for ascii in str.utf8 {
                                                                                              print(ascii)
                                                                                              }


                                                                                              Output:



                                                                                              83
                                                                                              119
                                                                                              105
                                                                                              102
                                                                                              116
                                                                                              32
                                                                                              115
                                                                                              116
                                                                                              114
                                                                                              105
                                                                                              110
                                                                                              103





                                                                                              share|improve this answer












                                                                                              Swift 4.2



                                                                                              The easiest way to get ASCII values from a Swift string is below



                                                                                              let str = "Swift string"
                                                                                              for ascii in str.utf8 {
                                                                                              print(ascii)
                                                                                              }


                                                                                              Output:



                                                                                              83
                                                                                              119
                                                                                              105
                                                                                              102
                                                                                              116
                                                                                              32
                                                                                              115
                                                                                              116
                                                                                              114
                                                                                              105
                                                                                              110
                                                                                              103






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Jul 14 '18 at 14:08









                                                                                              aios

                                                                                              10811




                                                                                              10811












                                                                                              • Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                                – Leo Dabus
                                                                                                Jul 17 '18 at 0:44




















                                                                                              • Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                                – Leo Dabus
                                                                                                Jul 17 '18 at 0:44


















                                                                                              Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                              – Leo Dabus
                                                                                              Jul 17 '18 at 0:44






                                                                                              Note that this will print also non ascii characters if present in the string. You can use string data method using ascii encoding to avoid invalid characters in the string use allowLossyConversion for ascii in str.data(using: .ascii, allowLossyConversion: true)! {
                                                                                              – Leo Dabus
                                                                                              Jul 17 '18 at 0:44













                                                                                              0














                                                                                              Swift 4



                                                                                              print("c".utf8["c".utf8.startIndex])


                                                                                              or



                                                                                              let cu = "c".utf8
                                                                                              print(cu[cu.startIndex])


                                                                                              Both print 99. Works for any ASCII character.






                                                                                              share|improve this answer


























                                                                                                0














                                                                                                Swift 4



                                                                                                print("c".utf8["c".utf8.startIndex])


                                                                                                or



                                                                                                let cu = "c".utf8
                                                                                                print(cu[cu.startIndex])


                                                                                                Both print 99. Works for any ASCII character.






                                                                                                share|improve this answer
























                                                                                                  0












                                                                                                  0








                                                                                                  0






                                                                                                  Swift 4



                                                                                                  print("c".utf8["c".utf8.startIndex])


                                                                                                  or



                                                                                                  let cu = "c".utf8
                                                                                                  print(cu[cu.startIndex])


                                                                                                  Both print 99. Works for any ASCII character.






                                                                                                  share|improve this answer












                                                                                                  Swift 4



                                                                                                  print("c".utf8["c".utf8.startIndex])


                                                                                                  or



                                                                                                  let cu = "c".utf8
                                                                                                  print(cu[cu.startIndex])


                                                                                                  Both print 99. Works for any ASCII character.







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Jan 16 '18 at 12:36









                                                                                                  PJ_Finnegan

                                                                                                  673710




                                                                                                  673710























                                                                                                      0














                                                                                                      There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.



                                                                                                      var singleChar = "a"
                                                                                                      UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])





                                                                                                      share|improve this answer





















                                                                                                      • Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                        – Leo Dabus
                                                                                                        Jul 17 '18 at 0:08


















                                                                                                      0














                                                                                                      There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.



                                                                                                      var singleChar = "a"
                                                                                                      UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])





                                                                                                      share|improve this answer





















                                                                                                      • Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                        – Leo Dabus
                                                                                                        Jul 17 '18 at 0:08
















                                                                                                      0












                                                                                                      0








                                                                                                      0






                                                                                                      There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.



                                                                                                      var singleChar = "a"
                                                                                                      UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])





                                                                                                      share|improve this answer












                                                                                                      There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.



                                                                                                      var singleChar = "a"
                                                                                                      UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])






                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered Jan 25 '18 at 5:51









                                                                                                      Anders

                                                                                                      213




                                                                                                      213












                                                                                                      • Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                        – Leo Dabus
                                                                                                        Jul 17 '18 at 0:08




















                                                                                                      • Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                        – Leo Dabus
                                                                                                        Jul 17 '18 at 0:08


















                                                                                                      Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                      – Leo Dabus
                                                                                                      Jul 17 '18 at 0:08






                                                                                                      Note that this is a non fallible initialiser. It will crash if you pass an invalid character which its value is out of the ascii range 0..<128. "Fatal error: Code point value does not fit into ASCII"
                                                                                                      – Leo Dabus
                                                                                                      Jul 17 '18 at 0:08













                                                                                                      0














                                                                                                      Swift 4+



                                                                                                      Char to ASCII



                                                                                                      let charVal = String(ch).unicodeScalars
                                                                                                      var asciiVal = charVal[charVal.startIndex].value


                                                                                                      ASCII to Char



                                                                                                      let char = Character(UnicodeScalar(asciiVal)!)





                                                                                                      share|improve this answer


























                                                                                                        0














                                                                                                        Swift 4+



                                                                                                        Char to ASCII



                                                                                                        let charVal = String(ch).unicodeScalars
                                                                                                        var asciiVal = charVal[charVal.startIndex].value


                                                                                                        ASCII to Char



                                                                                                        let char = Character(UnicodeScalar(asciiVal)!)





                                                                                                        share|improve this answer
























                                                                                                          0












                                                                                                          0








                                                                                                          0






                                                                                                          Swift 4+



                                                                                                          Char to ASCII



                                                                                                          let charVal = String(ch).unicodeScalars
                                                                                                          var asciiVal = charVal[charVal.startIndex].value


                                                                                                          ASCII to Char



                                                                                                          let char = Character(UnicodeScalar(asciiVal)!)





                                                                                                          share|improve this answer












                                                                                                          Swift 4+



                                                                                                          Char to ASCII



                                                                                                          let charVal = String(ch).unicodeScalars
                                                                                                          var asciiVal = charVal[charVal.startIndex].value


                                                                                                          ASCII to Char



                                                                                                          let char = Character(UnicodeScalar(asciiVal)!)






                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Nov 27 '18 at 16:15









                                                                                                          Mohit Kumar

                                                                                                          1355




                                                                                                          1355






























                                                                                                              draft saved

                                                                                                              draft discarded




















































                                                                                                              Thanks for contributing an answer to Stack Overflow!


                                                                                                              • Please be sure to answer the question. Provide details and share your research!

                                                                                                              But avoid



                                                                                                              • Asking for help, clarification, or responding to other answers.

                                                                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                                                                              To learn more, see our tips on writing great answers.





                                                                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                              Please pay close attention to the following guidance:


                                                                                                              • Please be sure to answer the question. Provide details and share your research!

                                                                                                              But avoid



                                                                                                              • Asking for help, clarification, or responding to other answers.

                                                                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                                                                              To learn more, see our tips on writing great answers.




                                                                                                              draft saved


                                                                                                              draft discarded














                                                                                                              StackExchange.ready(
                                                                                                              function () {
                                                                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29835242%2fwhats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va%23new-answer', 'question_page');
                                                                                                              }
                                                                                                              );

                                                                                                              Post as a guest















                                                                                                              Required, but never shown





















































                                                                                                              Required, but never shown














                                                                                                              Required, but never shown












                                                                                                              Required, but never shown







                                                                                                              Required, but never shown

































                                                                                                              Required, but never shown














                                                                                                              Required, but never shown












                                                                                                              Required, but never shown







                                                                                                              Required, but never shown







                                                                                                              Popular posts from this blog

                                                                                                              To store a contact into the json file from server.js file using a class in NodeJS

                                                                                                              Marschland

                                                                                                              Redirect URL with Chrome Remote Debugging Android Devices