so I have a string like this 0b00001 is there a way to turn that into an Int, I tried something like this,
let string = "0b0001"
let int = Int(string)
but since there is a "b" in the string to specify that it is binary it sets int to nil.
Is there any way to turn the contents of string into an int?
Yes. You can use BinaryInteger generic initializer but you need to drop the "0b" prefix:
init?<S>(_ text: S, radix: Int = 10) where S : StringProtocol
let str = "0b0101"
let int = Int(str.dropFirst(2), radix: 2) // 5
Related
I want to create a function that returns both text and integer. And I want to have an if loop inside this function. If the number of steps of the 1st user is more than the 2nd, the step difference of these two users and a text that says you are ahead should be returned.If the 2nd user has more steps than the 1st user, I want it to return a text saying that there is a difference in the number of steps between them and you are behind.
In my hand like this.
struct ActiveDuel{
let state: String
let user1StepCount: Int
let user2StepCount: Int
let user1Name: String
let user2Name: String
let user1Phote: String
let user2Phote: String
let stepDif: Int
let goldAmount: Int
let time: Int
let lastUpdateTime: Int
let startTime: Int
let docId: String
}
I created the code like this but it looks wrong and also doesn't contain text.
func DıfferenceStep(user1StepCount:Int , user2StepCount: Int ) -> Int{
if user1StepCount > user2StepCount {
let DıfferenceStepFunc = user1StepCount - user2StepCount
}else if user2StepCount > user1StepCount {
let DıfferenceFalseStep = user2StepCount - user1StepCount
}
}
I don't know how to use if statement inside functions and besides that I want it to return both integer and text.I would be glad if you help me in this regard.
Here is an example of your struct with a func inside it. You create the struct and then call the func on the struct instance.
struct ActiveDuel
{
var user1StepCount: Int = 0
var user2StepCount: Int = 0
var user1Name: String?
var user2Name: String?
func stepsDifference() -> Int
{
return abs(user1StepCount - user2StepCount)
}
}
let duel = ActiveDuel(user1StepCount: 30, user2StepCount: 5, user1Name: "Bill", user2Name: "Ted")
print(duel.stepsDifference())
I would consider making a Duelist struct and store each duelist's individual information in that instead of in the general ActiveDuel struct. Then you could have a Duel struct that had an active Bool property (true/false), and any number of Duelists (you could limit it to two).
Depending on how you use this it would be better to create 2 different computed properties in your ActiveDuell struct. One returning the difference in points and one returning a string that gives the information you want.
struct ActiveDuel{
let state: String
let user1StepCount: Int
let user2StepCount: Int
let user1Name: String
let user2Name: String
let user1Phote: String
let user2Phote: String
let stepDif: Int
let goldAmount: Int
let time: Int
let lastUpdateTime: Int
let startTime: Int
let docId: String
var pointDifference: Int{
// calculate the difference and make the result positive
abs(user1StepCount - user2StepCount)
}
var standings: String{
// if the difference is 0 the game is tied
if user1StepCount == user2StepCount{
return "you are tied"
} else {
// put the name of the leader and the points they lead in to the string
return "\(user1StepCount > user2StepCount ? user1Name : user2Name), you lead by \(pointDifference) points"
}
}
}
you can use it like this:
let activeDuel = ActiveDuel(user1StepCount: 12, user2StepCount: 10, user1Name: "Player1",.....
print(activeDuel.standings) // prints "Player1, you lead by 2 points
I'm trying to get the substring of the var num, but I need that substring be an Int How can I do that?
This is my code
func sbs_inicio(num: String, index: Int) -> Int{
let dato: Int = num.index(num.startIndex, offsetBy: index)
return dato
}
var num = "20932121133222"
var value = sbs_inicio(num: num, index: 2)
print(value) //value should be 20
Use the prefix function on the characters array
let startString = "20932121133222"
let prefix = String(startString.characters.prefix(2))
let num = Int(prefix)
Prefix allows you to get the first n elements from the start of an array, so you get these, convert them back to a String and then convert the resulting String to an Int
I am attempting to convert Int? to a String and assign it to a label without including the optional text. I currently have:
struct Choice: Mappable{
var id: String?
var choice: String?
var questionId: String?
var correct: Bool?
var responses: Int?
init?(map: Map) {
}
mutating func mapping(map: Map) {
id <- map["id"]
questionId <- map["questionId"]
choice <- map["choice"]
correct <- map["correct"]
responses <- map["responses"]
}
}
In the class accessing it
var a:String? = String(describing: self.currentResult.choices?[0].responses)
print("\(a!)")
and the output is:
Optional(1)
How would I make it just output 1 and remove the optional text?
a is an Optional, so you need to unwrap it prior to applying a String by Int initializer to it. Also, b needn't really be an Optional in case you e.g. want to supply a default value for it for cases where a is nil.
let a: Int? = 1
let b = a.map(String.init) ?? "" // "" defaultvalue in case 'a' is nil
Or, in case the purpose is to assign the possibly existing and possibly String-convertable value of a onto the text property of an UILabel, you could assign a successful conversion to the label using optional binding:
let a: Int? = 1
if let newLabelText = a.map(String.init) {
self.label.text = newLabelText
}
Why don't?
let a : Int = 1
var b = "\(a)"
print(b)
so
$ swift
[ 9> let a : Int = 1
a: Int = 1
[ 10> var b = "\(a)"
b: String = "1"
[ 11> print(b)
1
By the way there are other options like this one
12> var c = a.description
c: String = "1"
13> print(c)
1
In Swift, i cant cast Int to String by:
var iString:Int = 100
var strString = String(iString)
But my variable in Int? , there for error: Cant invoke 'init' with type '#Ivalue Int?'
Example
let myString : String = "42"
let x : Int? = myString.toInt()
if (x != null) {
// Successfully converted String to Int
//And how do can i convert x to string???
}
You can use string interpolation.
let x = 100
let str = "\(x)"
if x is an optional you can use optional binding
var str = ""
if let v = x {
str = "\(v)"
}
println(str)
if you are sure that x will never be nil, you can do a forced unwrapping on an optional value.
var str = "\(x!)"
In a single statement you can try this
let str = x != nil ? "\(x!)" : ""
Based on #RealMae's comment, you can further shorten this code using the nil coalescing operator (??)
let str = x ?? ""
I like to create small extensions for this:
extension Int {
var stringValue:String {
return "\(self)"
}
}
This makes it possible to call optional ints, without having to unwrap and think about nil values:
var string = optionalInt?.stringValue
If you need a one-liner it can be achieved by:
let x: Int? = 10
x.flatMap { String($0) } // produces "10"
let y: Int? = nil
y.flatMap { String($0) } // produces nil
if you need a default value, you can simply go with
(y.flatMap { String($0) }) ?? ""
EDIT:
Even better without curly brackets:
y.flatMap(String.init)
Apple's flatMap(_:) Documentation
Optional Int -> Optional String:
If x: Int? (or Double? - doesn't matter)
var s = x.map({String($0)})
This will return String?
To get a String you can use :
var t = s ?? ""
Hope this helps
var a = 50
var str = String(describing: a)
Crude perhaps, but you could just do:
let int100 = 100
println(int100.description) //Prints 100
Sonrobby, I believe that "Int?" means an optional int. Basically, by my understanding, needs to be unwrapped.
So doing the following works fine:
let y: Int? = 42
let c = String(y!)
That "!" unwraps the variable. Hope this helps!
As rakeshbs mentioned, make sure the variable won't be nill.
You need to "unwrap" your optional in order to get to the real value inside of it as described here. You unwrap an option with "!". So, in your example, the code would be:
let myString : String = "42"
let x : Int? = myString.toInt()
if (x != null) {
// Successfully converted String to Int
// Convert x (an optional) to string by unwrapping
let myNewString = String(x!)
}
Or within that conditional, you could use string interpolation:
let myNewString = "\(x!)" // does the same thing as String(x!)
For preventing unsafe optional unwraps I use it like below as suggested by #AntiStrike12,
if let theString = someVariableThatIsAnInt {
theStringValue = String(theString!))
}
Swift 3:
var iString:Int = 100
var strString = String(iString)
extension String {
init(_ value:Int){/*Brings back String() casting which was removed in swift 3*/
self.init(describing:value)
}
}
This avoids littering your code with the verbose: String(describing:iString)
Bonus: Add similar init methods for commonly used types such as: Bool, CGFloat etc.
You can try this to convert Int? to string
let myString : String = "42"
let x : Int? = myString.toInt()
let newString = "\(x ?? 0)"
print(newString) // if x is nil then optional value will be "0"
If you want an empty string if it not set (nil)
extension Int? {
var stringValue:String {
return self == nil ? "" : "\(self!)"
}
}
I have string variable:
var str = "239A23F"
How do I convert this string to a binary number?
str.toInt() does not work.
You can use NSScanner() from the Foundation framework:
let scanner = NSScanner(string: str)
var result : UInt32 = 0
if scanner.scanHexInt(&result) {
println(result) // 37331519
}
Or the BSD library function strtoul()
let num = strtoul(str, nil, 16)
println(num) // 37331519
As of Swift 2 (Xcode 7), all integer types have an
public init?(_ text: String, radix: Int = default)
initializer, so that a pure Swift solution is available:
let str = "239A23F"
let num = Int(str, radix: 16)