This question already has answers here:
How do I concatenate strings in Swift?
(21 answers)
Closed 7 years ago.
I would like to get final String like below:
var urlString = "http://testurl.com/contacts=["1111111","2222222"]"
There are three strings http://testurl.com/contacts= , 1111111 and 2222222
How to concatenate these strings in Swift
var str1 = "http://testurl.com/contacts="
var str2 = "1111111"
var str3 = "2222222"
var finalString = "\(str1)[\"\(str2)\",\"\(str3)\"]"
Related
This question already has answers here:
How to split an Int to its individual digits?
(11 answers)
Closed 3 years ago.
say for example i have an Int var firstInt = 23 what i need is i want to assign the value of firstInt to two separate variables so the output would be var x = 2 and var y = 3. i tried converting the firstInt to a string like so var strFirstInt = String(firstInt) and wanted to assign the first index of the string to a different variable and the second index to another variable and convert them to Int but i couldn't pick the string by index. so any ideas how to do this?
You can use .compactMap from String like this :
let numberInt = 23
let digits = String(numberInt).compactMap{ $0.wholeNumberValue}
Response :
[2, 3]
And with this array, you put the first member to the first var and seconds to another:
var x = digits[0]
var y = digits[1]
print("The decade is \(x) and units is \(y)")
Response:
The decade is 2 and units is 3
Convert the firstInt to String and then to Array,
var firstInt = 23
let arr = Array(String(firstInt)).map({ String($0 )})
Next, get the elements as per the index from array, i.e.
var x = Int(arr[0])
var y = Int(arr[1])
This question already has answers here:
swift How to remove optional String Character
(14 answers)
How to solve "String interpolation produces a debug description for an optional value; did you mean to make this explicit?" in Xcode 8.3 beta?
(8 answers)
Closed 5 years ago.
Novice in Swift and I'm having a frustrating problem. The program compiles correctly and runs without crashing. The program is supposed to calculate the age of a cat in cat years based user-inputted human years. After pressing the button, however, the result is diplayed with the word "Operator" appended by the cat years which is delimited by parenthesis, i.e., Optional(35). Here is my code:
#IBOutlet weak var getHumanYears: UITextField!
#IBOutlet weak var displayCatYears: UILabel!
#IBAction func calculateCatYears(_ sender: Any)
{
if let humanYears = getHumanYears.text
{
var catYears: Int? = Int(humanYears)
catYears = catYears! * 7
let catYearsString: String = String(describing: catYears)
displayCatYears.text = "Your cat is " + catYearsString + " years old"
}
}
Does anyone know what I'm doing wrong? Thank you for your valuable input!
The problem is here:
String(describing: catYears)
catYears is an Optional<Int>, a string that describes an Optional<Int> will be in the format of Optional(<value>) or nil. That's why you get Optional(35).
You need to unwrap catYears!
String(describing: catYears!)
Or, remove String(describing:) all together and do:
if let humanYearsText = getHumanYears.text, let humanYears = Int(humanYearsText)
{
let catYears = humanYears * 7
displayCatYears.text = "Your cat is \(catYears) years old"
}
As other mentioned, it is because var catYears: Int? = Int(humanYears), thus catYears is an optional. And the String(describing: ...) for an optional does print Optional(rawValue).
What you want is to make sure you have the value, and not an optional when you print it. If you're 100% certain that you do have a Int value in the string, you can do it with !.
However, I suggest that you don't use the ! operator because that will crash your application if there are characters in the textfield.
if let text = getHumanYears.text, let humanYears = Int(text)
{
let catYears = humanYears * 7
displayCatYears.text = "Your cat is \(catYears) years old"
} else {
displayCatYears.text = "I don't know!"
}
Unwrap catYearsString.
Use this
let catYearsString: String = String(describing: catYear!)
displayCatYears.text = "Your cat is " + catYearsString + " years old"
Output:
Test Code
var catYears: Int? = Int(7)
catYears = catYears! * 7
let catYearsString: String = String(describing: catYears!)
print("Your cat is " + catYearsString + " years old")
This question already has an answer here:
How to randomize the case of letters in a string in Swift? [closed]
(1 answer)
Closed 6 years ago.
Just want a way to capitalize letters in a sentence randomly. Is it possible?
Try this,
var string: String = "your string"
var chars: [Any] = []
var letterIndexes: [Any] = []
for i in 0..<string.characters.count {
var ch: unichar = string[i]
// add each char as a string to a chars collection
chars.append("\(ch)")
// record the index of letters
if CharacterSet.letters.characterIsMember(ch) {
letterIndexes.append((i))
}
}
select randomly from the letterIndexes to determine which letters will be upper case. Convert the member of the chars array at that index to uppercase.
var charsToUppercase: Int = 12
var i = 0
while i < charsToUppercase && letterIndexes.count {
var randomLetterIndex: Int? = arc4random_uniform(((letterIndexes.count) as? u_int32_t))
var indexToUpdate = CInt(letterIndexes[randomLetterIndex])
letterIndexes.remove(at: randomLetterIndex)
chars[indexToUpdate] = chars[indexToUpdate].uppercased()
i += 1
}
ow all that's left is to join the chars array into a string.
var result: String = (chars as NSArray).componentsJoined(byString: "")
print("\(result)")
Refer this link for more information.
This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 6 years ago.
I want to convert following String to NSMuableArray.
var components: String = "library/book/science"
For example, I want to perform the following objective c code in Swift
NSArray *componentsArray = [#"library/book/science" componentsSeparatedByString:#"/"];
NSMutableArray *componentsMutableArray = [[NSMutableArray alloc] initWithArray:componentsArray];
[componentsMutableArray addObject:#"astronomy"];
Here is your working swift code:
var components: String = "library/bool/science"
let componentsArray = components.componentsSeparatedByString("/") //["library", "bool", "science"]
let componentsMutableArray = NSMutableArray(array: componentsArray) //["library", "bool", "science"]
componentsMutableArray.addObject("astronomy") //["library", "bool", "science", "astronomy"]
var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")
You need to use NSString in order to call the componentsSeparatedByString function that will split your text into an array based on the separator of your choice.
let theString = NSString(string: "library/book/science")
let components = theString.componentsSeparatedByString("/")
This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
If I want to get a value from the NSString "😃hello World😃", what should I use?
The return value I want is "hello World".
The smileys can be any string. so i need some regexp to this.
There's more than one way to do it.
First: String in Swift 1.2 is bridged to NSString properly so the answer could be : How to get substring of NSString?
Second: This answer will deal with emoticon characters too.
var s = "😃hello World😃"
let index = advance(s.startIndex, 1) // index is a String.Index to the 2nd glyph, “h”
let endIndex = advance(s.startIndex, 12)
let substring=s[index..<endIndex] // here you got "hello World"
if let emojiRange = s[index...s.endIndex].rangeOfString("😃") {
let substring2 = s[index..<emojiRange.startIndex] // here you get "hello World"
}