swift How to remove optional String Character - string

How do I remove Optional Character
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString)
//http://hahaha.com/ha.php?color=Optional("Red")
I just want output "http://hahaha.com/ha.php?color=Red"
How can I do?
hmm....

Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var optionalVariable : String? // This is an optional.
optionalVariable = "I am a programer"
print(optionalVariable) // Optional("I am a programer")
var nonOptionalVariable : String // This is not optional.
nonOptionalVariable = "I am a programer"
print(nonOptionalVariable) // "I am a programer"
//There are different ways to unwrap optional varialble
// 1 (Using if let or if var)
if let optionalVariable1 = optionalVariable {
print(optionalVariable1)
}
// 2 (Using guard let or guard var)
guard let optionalVariable2 = optionalVariable else {
fatalError()
}
print(optionalVariable2)
// 3 (Using default value ?? )
print(optionalVariable ?? "default value") // If variable is empty it will return default value
// 4 (Using force caste !)
print(optionalVariable!) // This is unsafe way and may lead to crash

I looked over this again and i'm simplifying my answer. I think most the answers here are missing the point. You usually want to print whether or not your variable has a value and you also want your program not to crash if it doesn't (so don't use !). Here just do this
print("color: \(color ?? "")")
This will give you blank or the value.

You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:
if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
println(color) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString) // http://hahaha.com/ha.php?color=Red
}

In swift3 you can easily remove optional
if let value = optionalvariable{
//in value you will get non optional value
}

Check for nil and unwrap using "!":
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
if color != nil {
println(color!) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color!)"
println(imageURLString)
//"http://hahaha.com/ha.php?color=Red"
}

Besides the solutions mentioned in other answers, if you want to always avoid that Optional text for your whole project, you can add this pod:
pod 'NoOptionalInterpolation'
(https://github.com/T-Pham/NoOptionalInterpolation)
The pod adds an extension to override the string interpolation init method to get rid of the Optional text once for all. It also provides a custom operator * to bring the default behaviour back.
So:
import NoOptionalInterpolation
let a: String? = "string"
"\(a)" // string
"\(a*)" // Optional("string")
Please see this answer https://stackoverflow.com/a/37481627/6390582 for more details.

Try this,
var check:String?="optional String"
print(check!) //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
print(check) //Optional("optional string") //nil values are handled in this statement
Go with first if you are confident to have no nil in your variable.
Also, you can use if let or Guard let statement to unwrap optionals without any crash.
if let unwrapperStr = check
{
print(unwrapperStr) //optional String
}
Guard let,
guard let gUnwrap = check else
{
//handle failed unwrap case here
}
print(gUnwrap) //optional String

Simple convert ? to ! fixed my issue:
usernameLabel.text = "\(userInfo?.userName)"
To
usernameLabel.text = "\(userInfo!.userName)"

Although we might have different contexts, the below worked for me.
I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.
For example, print(documentData["mileage"]) is changed to:
print((documentData["mileage"])!)

import UIKit
let characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
var a: String = characters.randomElement()!
var b: String = characters.randomElement()!
var c: String = characters.randomElement()!
var d: String = characters.randomElement()!
var e: String = characters.randomElement()!
var f: String = characters.randomElement()!
var password = ("\(a)" + "\(b)" + "\(c)" + "\(d)" + "\(e)" + "\(f)")
print ( password)

when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !

How do I remove optional String Character for Printing in Swift UIkit
From These (Have Optional printing)
print("Collection Cell \(categories[indexPath.row].title) \(indexPath.row)")
To these ( Doesn't have Optional printing)
print("Collection Cell \(categories[indexPath.row].title ?? "default value") \(indexPath.row)")

print("imageURLString = " + imageURLString!)
just use !

You can just put ! and it will work:
print(var1) // optional("something")
print(var1!) // "something"

Related

Using loops to go through string and check char as a dict key

so I want to kind of build a "Decrypter", I have a dictionary with the keys being the symbol, and the value the respective value for the symbol, then I have this string that the code is suppose to look into, the translate will be saved in a other string, in this case called output. This is the way I did the loop part, but is not working:
var outputText = " "
for character in textForScan{
for key in gematriaToLetters{
if (gematriaToLetters.keys == textForScan[character]){
outputText.insert(gematriaToLetters.values, atIndex: outputText.endIndex)
}
}
}
You could also consider using map:
let outputText = "".join(map(textForScan) { gematriaToLetters[String($0)] ?? String($0) })
If you don't specify a specific letter in the dictionary it returns the current letter without "converting".
I think you are looking for something like this:
for aCharacter in textForScan {
let newChar = gematrialToLetters["\(aCharacter)"]
outputText += newChar
}
print(outputText)

Swift String.removeRange cannot compile

I don't understand what to do with the issue reported by the compiler. I tried to create a Range, but it says Index is not known:
//let range = matches.first!.range.location
let range = Range(
start:matches.first!.range.location,
end: matches.first!.range.location+matches.first!.range.length
)
id = text[range]
var t = text
t.removeRange(range)
return t
Compiler says: Cannot invoke 'removeRange' with an argument list of type '(Range)' on t.removeRange(range).
I'm pretty sure it's evident, but I lost a great deal of time on such a small issue… any help highly appreciated!
As your error says that:
Cannot invoke 'removeRange' with an argument list of type '(Range)'
Means there is a problem with your range instance type and removeRange function will only accept an argument with type Range<String.Index> and its syntax is :
/// Remove the indicated `subRange` of characters
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `count(self)`\ ).
mutating func removeRange(subRange: Range<String.Index>)
And here is working example with removeRange:
var welcome = "hello there"
let range = advance(welcome.endIndex, -6)..<welcome.endIndex
welcome.removeRange(range)
println(welcome) //hello
Hope this will help.
Swift 2.2 example of removing first 4 characters:
let range = text.startIndex..<text.startIndex.advancedBy(4)
text.removeRange(range)
That first line feels verbose. I hope newer Swift versions improve upon it.
Here is the working equivalent snippet:
static func unitTest() {
let text = "a👿bbbbb🇩🇪c"
let tag = Tag(id: "🇩🇪")
tag.regex = "👿b+"
print ("Unit test tag.foundIn(\(text)) ? = \(tag.foundIn(text))")
}
func foundIn(text: String) -> (id:String, remainingText:String)? {
// if a regex is provided, use it to capture, and keep the capture as a tag ID
if let regex = regex {
let r = Regex(regex) // text =~ regex
let matches = r.matches(text)
if matches.count >= 1 {
let first = matches.first!.range
let start = advance(text.startIndex, first.location)
let end = advance(start, first.length-1)
let range = Range(start: start, end: end)
id = text[range]
var t = text
t.removeRange(range)
return (id, t)
}
return nil
}
else if let range = text.rangeOfString(id) {
var t = text
t.removeRange(range)
return (id, t)
}
else {
return nil
}
}
The unit test returns :
Unit test tag.foundIn(a👿bbbbb🇩🇪c) ? = Optional(("👿bbbbb", "a🇩🇪c"))

Remove nth character from string

I have seen many methods for removing the last character from a string. Is there however a way to remove any old character based on its index?
Here is a safe Swift 4 implementation.
var s = "Hello, I must be going"
var n = 5
if let index = s.index(s.startIndex, offsetBy: n, limitedBy: s.endIndex) {
s.remove(at: index)
print(s) // prints "Hello I must be going"
} else {
print("\(n) is out of range")
}
While string indices aren't random-access and aren't numbers, you can advance them by a number in order to access the nth character:
var s = "Hello, I must be going"
s.removeAtIndex(advance(s.startIndex, 5))
println(s) // prints "Hello I must be going"
Of course, you should always check the string is at least 5 in length before doing this!
edit: as #MartinR points out, you can use the with-end-index version of advance to avoid the risk of running past the end:
let index = advance(s.startIndex, 5, s.endIndex)
if index != s.endIndex { s.removeAtIndex(index) }
As ever, optionals are your friend:
// find returns index of first match,
// as an optional with nil for no match
if let idx = s.characters.index(of:",") {
// this will only be executed if non-nil,
// idx will be the unwrapped result of find
s.removeAtIndex(idx)
}
Swift 3.2
let str = "hello"
let position = 2
let subStr = str.prefix(upTo: str.index(str.startIndex, offsetBy: position)) + str.suffix(from: str.index(str.startIndex, offsetBy: (position + 1)))
print(subStr)
"helo"
var hello = "hello world!"
Let's say we want to remove the "w". (It's at the 6th index position.)
First: Create an Index for that position. (I'm making the return type Index explicit; it's not required).
let index:Index = hello.startIndex.advancedBy(6)
Second: Call removeAtIndex() and pass it our just-made index. (Notice it returns the character in question)
let choppedChar:Character = hello.removeAtIndex(index)
print(hello) // prints hello orld!
print(choppedChar) // prints w

Defining a custom PURE Swift Character Set

So, using Foundation you can use NSCharacterSet to define character sets and test character membership in Strings. I would like to do so without Cocoa classes, but in a purely Swift manner.
Ideally, code could be used like so:
struct ReservedCharacters: CharacterSet {
characters "!", "#", "$", "&", ... etc.
func isMember(character: Character) -> Bool
func encodeCharacter(parameters) { accepts a closure }
func decodeCharacter(parameters) { accepts a closure }
}
This is probably a very loaded question. But I'd like to see what you Swifters think.
You can already test for membership in a character set by initializing a String and using the contains global function:
let vowels = "aeiou"
let isVowel = contains(vowels, "i") // isVowel == true
As far as your encode and decode functions go, are you just trying to get the 8-bit or 16-bit encodings for the Character? If that is the case then just convert them to a String and access there utf8 or utf16 properties:
let char = Character("c")
let a = Array(String(char).utf8)
println() // This prints [99]
Decode would take a little more work, but I know there's a function for it...
Edit: This will replace a character from a characterSet with '%' followed by the character's hex value:
let encode: String -> String = { s in
reduce(String(s).unicodeScalars, "") { x, y in
switch contains(charSet, Character(y)) {
case true:
return x + "%" + String(y.value, radix: 16)
default:
return x + String(y)
}
}
}
let badURL = "http://why won't this work.com"
let encoded = encode(badURL)
println(encoded) // prints "http://why%20won%27t%20this%20work.com"
Decoding, again, is a bit more challenging, but I'm sure it can be done...

Append Character to String in Swift

I'm trying to append Character to String using "+=", but It doesn't really work.
Once I tried with append method, it works. I just wonder why it is.
The compiler says "string is not identical to Unit8".
let puzzleInput = "great minds think alike"
var puzzleOutput = " "
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
// error : doesn't work
puzzleOutput += character
//puzzleOutput.append(character)
}
}
println(puzzleOutput)
20140818, Apple updated:
Updated the Concatenating Strings and Characters section to reflect the fact that String and Character values can no longer be combined with the addition operator (+) or addition assignment operator (+=). These operators are now used only with String values. Use the String type’s append method to append a single Character value onto the end of a string.
Document Revision History 2014-08-18
To append a Character to a String in Swift you can do something similar to the following:
var myString: String = "ab"
let myCharacter: Character = "c"
let myStringChar: String = "d"
myString += String(myCharacter) // abc
myString += myStringChar // abcd
Updated version
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput += String(character)
}
}
print(puzzleOutput)
// prints "grtmndsthnklk"

Resources