With Swift 3, according to your needs, you may choose one of the three following methods in order to solve your problem. Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.
Unsigned bit integer unsigned intprinted in hexadecimal using the digits 0—9 and uppercase A—F. Use uppercase X if you want A F and lowercase x if you want a Old answer for Swift 1: The conversion from an integer to a hex string can be done with. This does not require the import of any Framework and works with any base between 2 and The conversion from a hex string to an integer can be done with the BSD library function strtoul compare How to convert a binary to decimal in Swift?
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stridewithout sacrificing speed?
First note that your code does not detect invalid input data. For example, the string "XX" is just converted to a zero byte. Detecting invalid input with strtoul is a bit tricky, there is an alternative suggestion below. This does not change the performance.
The time to convert acharacter string is 0. I do not see an use-case for map here. But the performance can be improved considerably. As observed here and hereaccessing the UTF view of a Swift string is very fast. This leads to the following implementation:. Note that invalid input is still not detected. We can still make it faster by converting the UTF code points "manually" instead of using strtoul.
This is more code, but again faster, and also detects all kinds of invalid input:. The time to convert thecharacter string is now 0. This is more than 17 times faster than the original code. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. Asked 3 years, 8 months ago. Active 1 month ago. Viewed 14k times. Active Oldest Votes.
If that fails then the optional chaining data?. That is fine as far as I can see. There is also self. Martin R Martin R I hadn't even considered doing the manual nibble decoding.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. How do you output the value of NSData in Swift? Is it NSLogprint or println? So after trying a number of recommendations around the site, this is what actually ended up working for me. If you want just the bytes and don't know, or there isn't an appropriate string encoding you can still use NSLog in swift:.
Learn more. Printing NSData in Swift? Ask Question. Asked 5 years, 6 months ago. Active 3 years, 4 months ago.
Viewed 25k times. It seems I can just print the address of the object, and not the actual contents of it. User User Active Oldest Votes. This works without the NS prefix in Swift 2. Oct 5 '16 at Only works with legal ascii codes. Maxim Shoustin Maxim Shoustin Cargowire Cargowire 1, 8 8 silver badges 17 17 bronze badges. Sign up or log in Sign up using Google.
Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog.A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values.
The syntax for string creation and manipulation is lightweight and readable, with a string literal syntax that is similar to C.
You can also use strings to insert constants, variables, literals, and expressions into longer strings, in a process known as string interpolation.
This makes it easy to create custom string values for display, storage, and printing. Every string is composed of encoding-independent Unicode characters, and provides support for accessing those characters in various Unicode representations. Foundation also extends String to expose methods defined by NSString. This means, if you import Foundation, you can access those NSString methods on String without casting. You can include predefined String values within your code as string literals.
A string literal is a sequence of characters surrounded by double quotation marks ". If you need a string that spans several lines, use a multiline string literal—a sequence of characters surrounded by three double quotation marks:.
A multiline string literal includes all of the lines between its opening and closing quotation marks. The string begins on the first line after the opening quotation marks """ and ends on the line before the closing quotation marks, which means that neither of the strings below start or end with a line break:. To make a multiline string literal that begins or ends with a line feed, write a blank line as the first or last line.
For example:. A multiline string can be indented to match the surrounding code. The whitespace before the closing quotation marks """ tells Swift what whitespace to ignore before all of the other lines.
Subscribe to RSS
The middle line has more indentation than the closing quotation marks, so it starts with that extra four-space indentation. The code below shows four examples of these special characters. The wiseWords constant contains two escaped double quotation marks.
The dollarSignblackHeartand sparklingHeart constants demonstrate the Unicode scalar format:. Because multiline string literals use three double quotation marks instead of just one, you can include a double quotation mark " inside of a multiline string literal without escaping it. To include the text """ in a multiline string, escape at least one of the quotation marks.
You can place a string literal within extended delimiters to include special characters in a string without invoking their effect. You place your string within quotation marks " and surround that with number signs.
String literals created using extended delimiters can also be multiline string literals. You can use extended delimiters to include the text """ in a multiline string, overriding the default behavior that ends the literal.
To create an empty String value as the starting point for building a longer string, either assign an empty string literal to a variable, or initialize a new String instance with initializer syntax:. Find out whether a String value is empty by checking its Boolean isEmpty property:. In each case, a new copy of the existing String value is created, and the new copy is passed or assigned, not the original version.
This means you always get great performance when working with strings as value types. You can access the individual Character values for a String by iterating over the string with a for - in loop:.It supports Unicode strings, characters, and identifier names. The swiftc compiler can emit compiler warnings, error messages, or verbose messages. The Foundation Data class is recommended to handle raw bytes in memory, and to read and write binary data in Swift.
This approach is recommended if you do not read textual data and to prevent a loss of information from possible conversion of data to UTF When you write Swift applications, it is important to remember that all strings are represented as Unicode in Swift.
The to: parameter accepts an output stream to receive the text representation of each item to be printed.
On the other hand, you can avoid this heuristic and be explicit in the conversion by using the zOSSwift. This parameter specifies that input data will be converted from the specified encoding to the UTF-8 Internal swift encoding.
The following example demonstrates how to write a text file using the Foundation FileManager extensions. The text is written in the ebcdic encoding.
If you inspect the resulting file ebcdic. To read the file, you must create a new instance of a string with the path as a parameter to the constructor. If you compile with swiftc ebcdic. The following example illustrates how to write binary data using an array of bytes.
It then reads the created binary file and converts it into a Data object. FileHandle forWritingTo: purl fh. Data contentsOf: purl print "Iterating and printing out each byte" data. If you compile with swiftc bin. This command tags a file with the appropriate codepage. Once tagged, a file can be read by file reading commands such as cat or vi.Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers, Double and Float for floating-point values, Bool for Boolean values, and String for textual data.
How to convert Data to a String
Swift also provides powerful versions of the three primary collection types, ArraySetand Dictionaryas described in Collection Types.
Like C, Swift uses variables to store and refer to values by an identifying name. These are known as constants, and are much more powerful than constants in C. In addition to familiar types, Swift introduces advanced types not found in Objective-C, such as tuples.
Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value. Swift also introduces optional types, which handle the absence of a value. Using optionals is similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with.
If part of your code requires a Stringtype safety prevents you from passing it an Int by mistake.
Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that requires a non-optional String. Type safety helps you catch and fix errors as early as possible in the development process. Constants and variables associate a name such as maximumNumberOfLoginAttempts or welcomeMessage with a value of a particular type such as the number 10 or the string "Hello".
You declare constants with the let keyword and variables with the var keyword. Then, declare a new variable called currentLoginAttemptand give it an initial value of 0.
In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt. Use variables only for storing values that need to be able to change. You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store.
Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use. This example provides a type annotation for a variable called welcomeMessageto indicate that the variable can store String values:.
The welcomeMessage variable can now be set to any string value without error:. You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value. Nor can they begin with a number, although numbers may be included elsewhere within the name.
Nor can you change a constant into a variable or a variable into a constant. However, avoid using keywords as names unless you have absolutely no choice. You can change the value of an existing variable to another value of a compatible type.
In this example, the value of friendlyWelcome is changed from "Hello! Attempting to do so is reported as an error when your code is compiled:.
Note: The 2 in this example is the field width and represents the minimum length desired. The 0 tells it to pad the result with leading 0 's if necessary. Without the 0the result would be padded with leading spaces.
Of course, if the result is larger than two characters, the field length will not be clipped to a width of 2 ; it will expand to whatever length is necessary to display the full result. This isn't a problem if you're doing iOS or macOS programming. Use uppercase X if you want A F and lowercase x if you want a If you want to print integer values larger than UInt With Swift 5, according to your needs, you may choose one of the three following methods in order to solve your problem.
Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.
Unsigned bit integer unsigned intprinted in hexadecimal using the digits 0—9 and uppercase A—F. In Swift3 import foundation is not required, At least not in a Project. String should have all the functionality as NSString.
Answers above work fine for values in the range of a 32 bit Int, but values over this won't work as the value will roll over. You need to use the length modifier for values greater than a 32bit Int. Learn more. Asked 5 years, 10 months ago.
Active 9 months ago. Viewed 58k times.Modifying the Array - Introduction to Algorithms & Data Structures in Swift 4
Suragch k gold badges silver badges bronze badges. Based on the answer by stackoverflow.
Subscribe to RSS
Active Oldest Votes. KevinSliech, I'll admit that it is ambiguous. I meant it as if someone came up and asked, "what does 7B represent? The ambiguity might goof up folks not well versed in alternate number systems. KevinSliech, thanks.
I made the statement clearer. Rich Rich 7, 5 5 gold badges 38 38 silver badges 54 54 bronze badges. How can i convert this String to UInt? Imanou Petit Imanou Petit Goodtime Goodtime 3 3 bronze badges. MikeJ MikeJ 1, 2 2 gold badges 13 13 silver badges 17 17 bronze badges. Please add code to convert hex back to decimal too.