0

Why i received error when trying to print var(Short code)

CANT PRINT VARIABLE IN LAST LINE import Foundation func string_a(_ input: String) -> String { var chars = input let index_start = chars.index(after: chars.startIndex) let index_end = chars.index(before: chars.endIndex) let middleRange = index_start ..< index_end var sub_string = chars [middleRange] var newString = String (sub_string) //IT WONT PRINT THIS while sub_string.contains("a") { sub_string.remove(at: sub_string.firstIndex(of: "a")!) } chars.replaceSubrange(middleRange, with: sub_string) return String(chars) } print(string_a("abcaad")) print(string_a("abcada")) print(newString) //Errmsg: Cannot find newString in scope

18th Apr 2021, 9:24 PM
Dzondzula
Dzondzula - avatar
2 Réponses
+ 3
newString only exists withing the scope of the function string_a(). It cannot be accessed outside of the function.
18th Apr 2021, 9:42 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
You can print it from inside the function. Put the print statement under the line where newString is defined.
18th Apr 2021, 9:48 PM
Coding Cat
Coding Cat - avatar