I have this code
var i = 1
println(i) //result is 1
println(%02i) //is wrong
I want it to output 01 instead of 1
Unfortunately, you can't format swift strings like that (as far as I know.) You can try to use an NSString though.
println(NSString(format:"%02i", i))
This is it
var i = 1
NSLog("%02d", i)
O/P - 01
Your best bet is still going to be NSString formatting:
var i = 3
println("someInt is now \(i)")
// prints "someInt is now 1"
println(NSString(format:"%.2f",i))
// prints "someInt is now 01"
May be this help you.
var i = 1
println("0\(i)")
//01
Related
Prior to the new Swift version I was using the following code in my app.
Now it launches an exception.
for (i, in 0 ..< len){
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
XCode says:
Expected pattern
Expected "," separator
Expected "in" after for-each pattern
Expected SequenceType expression for for-each loop
Changing the code with the proposed solutions doesn't change the exceptions thrown.
Any help is welcome to update the code to the current Swift version.
For for syntax you are using have been deprecated, and should be changed to
for _ in 0..<len
// rest of your code
the question already has correct answer still i have converted it so posting here may be some get help from it
let len = 5
let letters:NSString = "str"
for i in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
let randomString:NSMutableString = ""
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
As some of the variable are not shown in the code i have made them based on the parameters
So I have an array of elements of type float. And I have a UILabel which is supposed to display each of these elements of the array on DIFFERENT LINES.
The Array is
var history = [Float]()
I used a for loop to go through each element and append it to the UILabel
for(i=0; i<size; i++){
currentString = String(history[i])
result.text = result.text! + "\n" + currentString
}
result is the UILabel.
I tried using \n but it doesn't seem to recognise it. Any solutions for this in Swift. Thanks in advance!
You can try below to solve your issue.
let history = [1.0, 2.0, 3.0, 4.0]
var result = ""
self.lbl.text = ""
for var i=0; i < history.count; i++
{
let currentString = NSString(format: "%.2f", history[i])
self.lbl.text = self.lbl.text! + "\n" + (currentString as String)
}
And Line Number should be 0. I set that from XIB.
Thanks
The first thing I would check is if your label has (it is stupid mistake, but can happen to all of us)
label.numberOfLines = 0
Assuming that is true, instead of building the string by hand, you could use in-built function join(). Sadly, since it is not String array, you can't use it directly, but you have to create string array first
// Get both storages
var history = [Float]() // Filled with your data
var stringHistory = [String]()
// Convert each number to string
for value in history {
stringHistory.append(String(value))
}
// Finally, join array to one string using \n as separator
let finalString = "\n".join(stringHistory)
Hope some of this helps!
I use swift and what i want to do is to check this:
if string.characterAtIndex(i) == "a"
But i get error. How to convert this "a" so that can be same type with characters i loop.
Thanks.
You need to convert you UniChar - characterAtIndex(i) to a Character, so you can compare them.
Solution:
let ithChar:Character = Character(UnicodeScalar(string.characterAtIndex(i)))
if ithCahr == "a"
{
//do some stuff
}
Hope it helps!
Here is another way you could do it:
if string.characterAtIndex(i) == "a".characterAtIndex(0)
In better explanatory way, this can be one of the ways to perform what you intend to do.
var str = "Hello, playground"
var newString = str as NSString
var num:Int = countElements(str)
for var i = 0; i < num; i++
{
if ( Array(str)[i] == "p") {
println(Array(str)[i]) // will show the output
println("success");
break;
}
}
I know I can initialize an array of Ints for example like:
var intArray = [Int](count: 10, repeatedValue: 0)
What I want to do is something like this:
var array = Array(count:6, repeatedValue:Array(count:0, repeatedValue:AnyObject()))
(Xcode returns with: AnyObject cannot be constructed because it has no accessible initializers)
With the same outcome as I could initialize the array like:
var anyObjectArray : [[AnyObject]] = [[],[],[],[],[],[]]
But doing the above is ugly if i need like 100 rows of lets say 3
The problem is I can append in my function like:
// init array
var anyObjectArray : [[AnyObject]] = [[],[],[]]
//inside a for loop
anyObjectArray[i].append(someValue)
That works ok, until of course i gets higher then the number of rows in the array.
A answer to this problem is also acceptable if I could do something like:
anyObjectArray[append a empty row here][]
But that is probably stupid :)
I hope there is a way to do this cause I don't feel like having a line like:
var anyObjectArray : [[AnyObject]] = [ [],[],[],[],[],[],[],[],[],[],[],[],[],[],[], ... etc ]
at the top of my page ;)
Thank you for your time!
You don't need the second repeatedValue initialiser, since you want an empty array. You can just use
var array = Array(count:6, repeatedValue:[AnyObject]())
You can try with 2 loops, working as a grid :
var items: = Array<Array<Item>>()
for col in 0..<maxCol {
var colItems = Array<Item>()
for row in 0..<maxRow {
colItems.append(Item())
}
items.append(colItems)
}
//Append as much as you want after
Try this
let columns = 27
let rows = 52
var array = Array<Array<Double>>()
for column in 0... columns {
array.append(Array(count:rows, repeatedValue:Int()))
}
Try using this
let array = Array(count:6, repeatedValue:[])
for (var i=0; i<array.count; i++){
array[i] = Array(count:0, repeatedValue: AnyObject.self)
}
in place of your code.
Swift 3:
var array = Array(repeating:[AnyObject](),count:6)
I'm trying to add zero-padding to a number. I did some searching and can't find an obvious way to do this. Am I missing something?
Dart 1.3 introduced a String.padLeft and a String.padRight you can use :
String intToString(int i, {int pad 0}) => i.toString().padLeft(pad, '0');
You can use the String function .padLeft(Int width, [String = ' '])
https://api.dartlang.org/apidocs/channels/dev/dartdoc-viewer/dart-core.String#id_padLeft
int i = 2;
print(i.toString().padLeft(2, "0"));
result: 02
I don't think you're missing anything, there's a big lack of formatting functions right now. I think the best you can do is something like:
String intToString(int i, {int pad: 0}) {
var str = i.toString();
var paddingToAdd = pad - str.length;
return (paddingToAdd > 0)
? "${new List.filled(paddingToAdd, '0').join('')}$i" : str;
}
Obviously something that took a format string would be much nicer. Feature request?