How to convert an Int to a Character in Swift
You can't convert an integer directly to a Character
instance, but you can go from integer to UnicodeScalar
to Character
and back again:
let startingValue = Int(("A" as UnicodeScalar).value) // 65
for i in 0 ..< 26 {
print(Character(UnicodeScalar(i + startingValue)))
}
Converting Integer to Character in Swift
You can achieve the same thing in Swift like this:
let a = Character(UnicodeScalar(0 + 97))
let b = Character(UnicodeScalar(1 + 97))
SWIFT 3 - Convert Integer to Character
You can extend Int to return the desired associated character as follow:
extension Int {
var associatedCharacter: Character? {
guard 1...10 ~= self, let unicodeScalar = UnicodeScalar(64 + self) else { return nil }
return Character(unicodeScalar)
}
}
1.associatedCharacter // A
2.associatedCharacter // B
3.associatedCharacter // C
10.associatedCharacter // J
11.associatedCharacter // nil
Swift: how to convert array of Int into array of Characters?
Try this:
Array(0...9).map({String($0)}).map({ Character($0) })
In the code above, we are taking each Int
from [Int]
, transform it into String
using the String constructor/initializer (in order words we're applying the String initializer (a function that takes something and returns a string) to your [Int]
using map
an higher order function), once the first operation is over we'd get [String]
, the second operation uses this new [String]
and transform it to [Character]
.
if you wish to read more on string visit here.
@LeoDabus proposes the following:
Array(0...9).map(String.init).map(Character.init) //<-- no need for closure
Or instead of having two operations just like we did earlier, you can do it with a single iteration.
Array(0...9).map({Character("\($0)")})
@Alexander proposes the following
Array((0...9).lazy.map{ String($0) }.map{ Character($0) })
(0...9).map{ Character(String($0)) } //<-- where you don't need an array, you'd use your range right away
Converting to Char/String from Ascii Int in Swift
It may not be as clean as Java, but you can do it like this:
var string = ""
string.append(Character(UnicodeScalar(50)))
You can also modify the syntax to look more similar if you like:
//extend Character so it can created from an int literal
extension Character: IntegerLiteralConvertible {
public static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character {
return Character(UnicodeScalar(value))
}
}
//append a character to string with += operator
func += (inout left: String, right: Character) {
left.append(right)
}
var string = ""
string += (50 as Character)
Or using dasblinkenlight's method:
func += (inout left: String, right: Int) {
left += "\(UnicodeScalar(right))"
}
var string = ""
string += 50
Convert Int to String in Swift
Converting Int
to String
:
let x : Int = 42
var myString = String(x)
And the other way around - converting String
to Int
:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
How to convert a character to an integer in Swift 3
It's as simple as this.
let myString = "5"
let sum = 3 + Int(myString)! // Produces 8
print(Int(myString)!)
Indexing
let str = "My test String Index"
let index = str.index(str.startIndex, offsetBy: 4)
str[index] // Returns e from test
let endIndex = str.index(str.endIndex, offsetBy:-2)
str[Range(index ..< endIndex)] // returns String "est String Ind"
str.substring(from: index) // returns String "est String Index"
str.substring(to: index) // returns String "My t"
Convert Character to Int in Swift 2.0
In Swift 2.0, toInt()
, etc., have been replaced with initializers. (In this case, Int(someString)
.)
Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (Int?
) instead of just an Int
. The best thing to do is unwrap this optional using if let
.
I'm not sure exactly what you're going for, but this code works in Swift 2, and accomplishes what I think you're trying to do:
let unsolved = "123abc"
var fileLines = [Int]()
for i in unsolved.characters {
let someString = String(i)
if let someInt = Int(someString) {
fileLines += [someInt]
}
print(i)
}
Or, for a Swiftier solution:
let unsolved = "123abc"
let fileLines = unsolved.characters.filter({ Int(String($0)) != nil }).map({ Int(String($0))! })
// fileLines = [1, 2, 3]
You can shorten this more with flatMap
:
let fileLines = unsolved.characters.flatMap { Int(String($0)) }
flatMap
returns "an Array
containing the non-nil results of mapping transform
over self
"… so when Int(String($0))
is nil
, the result is discarded.
How to convert Characters to Int in Swift 4?
for number in numbers!
This line of code extracts each character
in the string
(223 345 567)
and tries to convert it to int
. That's why it converts each valid number in string and left the spaces.
You need to first split the string
in to array
of string
numbers then iterate through the array to convert them.
Split it, further iterate through strNumArray
and convert them to integers
var array = [Int]()
if let strNumArray = numbers?.components(separatedBy: " ") {
for number in strNumArray {
if let integer = Int(String(number)) {
array.append(integer)
}
}
}
print(array)
And in more swifty way
var arrayInt = numbers.split(separator: " ").map{Int($0)}
Related Topics
Swiftui: Set Status Bar Color for a Specific View
How to Save List of Object in User Default
Xcode UI Testing Error Keyboard
How to Make an iOS Asset Bundle
Uicollectionview Insert Cells Above Maintaining Position (Like Messages.App)
Modify Uiimage Renderingmode from a Storyboard/Xib File
Navigation Pop View When Swipe Right Like Instagram iPhone App.How I Achieve This
How to Set Aspect Ratio Constraints Programmatically in iOS
How to Get Directions in Mkmapview Using a Built in Apple API
Dismissing Both Uinavigation Views and Modal Views at Once Programmatically
Xcode 8.1 Push Notifications in Swift 2.3 with Firebase Integration Not Getting
Datefromstring Returns Nil for Some Values
Creating Thumbnail from Local Video in Swift
Why Is There an Frame Rectangle and an Bounds Rectangle in an Uiview
How to Disable Horizontal Scrolling of Uiscrollview