Exc-bad-instructs, how can I fix this?


let aphabet = ["0","1","2","3","4","5","6","7","8","9","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","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"]

let smallCaps = ["0","1","2","3","4","5","6","7","8","9","ᴀ","ʙ","ᴄ","ᴅ","ᴇ","ғ","ɢ","ʜ","ɪ","ᴊ","ᴋ","ʟ","ᴍ","ɴ","ᴏ","ᴘ","ǫ","ʀ","s","ᴛ","ᴜ","ᴠ","ᴡ","x","ʏ","ᴢ","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"]

func smallCapsFunc(text:String) -> String{

var charArray = text.components(separatedBy: "")

var i = 0

while i<charArray.count {

var letter:Int = aphabet.firstIndex(of: charArray[i])!

charArray[i] = smallCaps[letter]

i+=1

}

var string = charArray.joined(separator: "")

return string

}

smallCapsFunc(text: "hello")


If you have a clue please help me.

Thank you

You have not learnt anything in your previous questions...


When you show error message, better take more parts of the error info shown in the debug console:


Please show whole error message shown in the debug console.

The whole error message shows:


Fatal error: Unexpectedly found nil while unwrapping an Optional value: file MyPlayground.playground, line 9

Thanks for showing the message.


I guess your Playground's line 9 is at this line:

        var letter:Int = aphabet.firstIndex(of: charArray[i])!

You use forced-unwrapping `!` here, but I recommend to avoid that as far as you can.


When you want to safely-unwrap Optionals, you can use:

- Conditional binding, in short, so-called `if-let`

- Nil coalescing operator `??`


In this case, you need to define the behavior in case of `firstIndex(of:)` returning nil.

So, Conditional binding seems to be more appropriate.


Replace these two lines:

        var letter:Int = aphabet.firstIndex(of: charArray[i])!
        charArray[i] = smallCaps[letter]

with:

        if let letterIndex = aphabet.firstIndex(of: charArray[i]) {
            charArray[i] = smallCaps[letterIndex]
        }


This change prevents the runtime error Fatal error: Unexpectedly found nil while unwrapping an Optional value, but that does not mean you would get an expected result.


As I said before, `components(separatedBy:)` is not a good tool here and `charArray` cannot be an Array of characters.

You may need to rewrite your code to get Hᴇʟʟᴏ from `smallCapsFunc(text: "Hello")`.

unwrapping "by force" is always dangerous.


either use :

if let value = oprionalValue


of let value = optionalValue ?? defaultValue

Exc-bad-instructs, how can I fix this?
 
 
Q