subscript' is unavailable: cannot subscript String with a CountableClosedRangeInt, see the documentation comment for discussion
- If you want to use subscripts on Strings like
"palindrome"[1..<3]
and"palindrome"[1...3]
, use these extensions.
Swift 4
extension String {
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
Swift 3
For Swift 3 replace with return self[start...end]
and return self[start..<end]
.
- Apple didn't build this into the Swift language because the definition of a 'character' depends on how the String is encoded. A character can be 8 to 64 bits, and the default is usually UTF-16. You can specify other String encodings in
String.Index
.
This is the documentation that Xcode error refers to.
More on String encodings like UTF-8 and UTF-16
subscript is unavailable: cannot subscript String with an Int
Seeing other parts of your code in BenchmarkWODViewController.swift, you need to modify your prepareForSegue
as follows:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showBenchmarkDetail" {
let controller = segue.destinationViewController as? BenchmarkWODDetailView
if let indexPath = self.tableView.indexPathForSelectedRow
{
//This should be consistent with your `tableView(_:cellForRowAtIndexPath:)`.
let wod = FilteredWodList[indexPath.row]
controller?.nameText = wod.name ?? ""
controller?.descriptionText = wod.description ?? ""
controller?.exerciseText = wod.exercise ?? ""
}
}
}
Key points are already found in Leo Dabus's comments.
No exact matches in call to subscript [Swift]
Actually you should get the error
Cannot subscript a value of type '[String : Int]' with an argument of type 'String.Element' (aka 'Character')
str
is obviously String?
, the element type when enumerating a string is Character
but the subscription type must be String
.
let dic = ["a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26]
for i in str ?? "" { // no need for var i
let ci = dic[String(i)] ?? 0
print(ci)
}
If the string contains a character which is not in the dictionary the result is 0.
There is a shorter way without a helper dictionary
for i in str ?? "" where ("a"..."z") ~= i {
let ci = Int(i.asciiValue!) - 96
print(ci)
}
Beginner: When working with arrays, why does this work but not this?
The issue is that with an array, the subscript operator does not return an optional, so it makes no sense to use an unwrapping construct like if let
to unwrap it.
Try let foo = colorsArray[42]
, where the index is out of bounds. It doesn’t return nil
, but rather will just crash with an “subscript out of range” error. As the documentation says (emphasis added):
Use the
first
andlast
properties for safe access to the value of the array’s first and last elements. If the array is empty, these properties arenil
....
You can access individual array elements through a subscript. The first element of a nonempty array is always at index zero. You can subscript an array with any integer from zero up to, but not including, the count of the array. Using a negative number or an index equal to or greater than count triggers a runtime error.
So, the last
provides safe access, returning an optional, but the subscript operator doesn’t return an optional, but also doesn’t provide safe access if you supply an invalid index.
How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator
You should leave one side empty, hence the name "partial range".
let newStr = str[..<index]
The same stands for partial range from operators, just leave the other side empty:
let newStr = str[index...]
Keep in mind that these range operators return a Substring
. If you want to convert it to a string, use String
's initialization function:
let newStr = String(str[..<index])
You can read more about the new substrings here.
Related Topics
How to Inject .Environmentobject() in Watchos6
How to Change the Appearance of the Datepicker in the Swiftui Framework to Only Months and Years
How to Call a Func Within a Closure
Ios13 Uialertcontroller with Custom View & Preferredstyle as Actionsheet Grayscale All Colors
Why Does the Compiler Not See the Default Code in a Protocol
How to Make Exponents in the Swiftui
How to Retrieve Audio File from Parse Swift
Swiftui Mysterious Spacing Between Large Text and Textfield in VStack
Cannot Stop Background Music from Within Game Scenes, Swift 3/Spritekit
Fetch an Email Body in Mailcore2 Osx with Swift
How to Generate a Random Unicode Character in Swift
Different Path Url for Filemanager Everytime I Open the App
Url Constructor Doesn't Work with Some Characters
Unrecognized Selector Sent to Instance When No Related Entities Found in Core Data