Cannot Subscript a value of type '[String]' with an index of type 'String'
In your first loop, you are doing
for x in pokemon
This casts each value in pokemon
to x
.
You don't need to subscript pokemon[x]
as x
is not an index, it is the element.
Naturally, you would get the error you got because:
- pokemon
is an array of strings
- x
is an element in pokemon
(which makes it a string).
With this loop, this is happening in your code:
pokemon["snorlax"]
As arrays are subscriptable only by integer, this is invalid.
For this loop, one only needs to
name = x
to cast the value of the currently iterated element of pokemon
to the variable.
In your second loop, you're iterating through an integer sequence (range).
for x in 1..<pokemon.count
The range 1..<pokemon.count
gives x
the value of 1, 2, 3... and so on per iteration until you reach one less than the count of Pokemons in the array.
This works because you are now subscripting array pokemon
to an integer value of x
.
With this loop, this is happening in your code:
pokemon[1] // contains string "snorlax"`
Also, I'm not sure if this is a mistake in your code but starting the range at 1 means that you'll exclude the first element of a zero-indexed array, in which the first element is 0.
Cannot subscript a value of type '[[String : Any]]' with an index of type 'String'
[[String:Any]]
is an array. It can be only subscripted by Int
index.
You have to iterate over the array for example:
if let reviews = place.details?["reviews"] as? [[String:Any]] {
for review in reviews {
if let authorName = review["author_name"] as? String {
// do something with authorName
}
}
}
Why I Cannot subscript a value of type '[String : [String]]' with an argument of type 'String.SubSequence' (aka 'Substring')?
You can simply use Dictionary's
init(grouping:by:)
initializer
like so,
var animalsDict = Dictionary(grouping: animals) { String($0.first!) }
var animalSectionTitles = animalsDict.keys.sorted()
Output:
print(animalsDict) //["G": ["Giraffe", "Greater Rhea"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "E": ["Emu"], "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "R": ["Rhinoceros"], "D": ["Dog", "Donkey"], "B": ["Bear", "Black Swan", "Buffalo"], "M": ["Manatus", "Meerkat"], "W": ["Whale", "Whale Shark", "Wombat"], "S": ["Seagull"], "T": ["Tasmania Devil"], "C": ["Camel", "Cockatoo"]]
print(animalSectionTitles) //["B", "C", "D", "E", "G", "H", "K", "L", "M", "P", "R", "S", "T", "W"]
Cannot subscript a value of type '[String : String]' with an index of type 'Int'
In the below code,
var menuItems:[String:String] = ["image1":"Order", "image2":"Notifications", "image3":"Free orders", "image4":"Payment", "image5":"Help", "image6":"Settings"]
menuItems
is a Dictionary
. Since it is a dictionary
, the items in it will be unordered. So, whenever you try to get an element from it based on indexPath
, you might get different result each time.
Reason for error:
Also, since it is a Dictionary
of type [String:String]
, you definitely cannot get the elements from it using an Int
, i.e. indexPath.row
as the subscript
. That's the reason you're getting the error.
Solution:
Instead, you must create a separate type - class/struct
to store a single menuItem
.
struct MenuItem {
let pageIcon: String
let pageName: String
}
Now, the menuItems
array
will be of type [MenuItem]
,
var menuItems = [MenuItem]()
menuItems.append(MenuItem(pageIcon: "image1", pageName: "Order"))
menuItems.append(MenuItem(pageIcon: "image2", pageName: "Notifications"))
menuItems.append(MenuItem(pageIcon: "image3", pageName: "Free orders"))
menuItems.append(MenuItem(pageIcon: "image4", pageName: "Payment"))
menuItems.append(MenuItem(pageIcon: "image5", pageName: "Help"))
menuItems.append(MenuItem(pageIcon: "image6", pageName: "Settings"))
menuItems
will contain the MenuItem
objects containing the required data. Use menuItems
as dataSource
of tableView
.
Now, in tableView(_: cellForRow:)
, you can get the menuItem
like,
cell.pageIcon.image = UIImage(named: menuItems[indexPath.row].pageIcon)
cell.pageName.text = menuItems[indexPath.row].pageName
Cannot subscript a value of type '[String : String]?' with an index of type 'String'
The error is because you're trying to use the subscript on an optional value. You're casting to [String: String]
but you're using the conditional form of the casting operator (as?
). From the documentation:
This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.
Therefore orch
is of type [String: String]?
. To solve this you need to:
1. use as!
if you know for certain the type returned is [String: String]
:
// You should check to see if a value exists for `orch_array` first.
if let dict: AnyObject = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] {
// Then force downcast.
let orch = dict as! [String: String]
orch[appleId] // No error
}
2. Use optional binding to check if orch
is nil
:
if let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String: String] {
orch[appleId] // No error
}
Hope that helps.
Cannot subscript a value of type '[String : Int]' with an index of type 'String?'
The error indicates, that MUser.sharedInstance.getUserId()
returns an optional.
You need to unwrap this:
self.books = self.books.filter {
guard let userID = MUser.sharedInstance.getUserId() else { return false }
return $0.completed[userID] ?? 0 > 0
}
Swift 4: Cannot subscript a value of type 'String' with an index of type 'CountablePartialRangeFromInt'
Whoops. Seems I needed to just do this:
let idx = response.index(response.startIndex, offsetBy: 11)
let substr = response[idx...]
Related Topics
Shared Cookies with Wkprocesspool for Wkwebview in Swift
How to Create Public Extensions, in a Shared Framework, for Xctest
Typecast Unsafemutablepointer<Void> to Unsafemutablepointer<#Struct Type#>
Nsurlsessiondatadelegate Method Didreceivedata and Others Are Not Called
Nskeyedunarchiver Fails to Decode a Custom Object in Swift
Accessing Swift Set Elements by Their Hash Value
How to Cast an @Binding in Swift
Swift. Get Binary String from an Integer
Self Refrence Inside Swift Closure Return Nil Some Time
Compiler Cannot Infer Return Type
Modal Picker Not Scrolling Right Swiftui
How to Immediately See Swift Errors in Appcode
What Might Be Causing This Animation Bug with Swiftui and Navigationview
More Concise Way to Nest Enums for Access by Switch Statements in Swift
Xcode UI Test:Accessibility Query Fail on Uitableviewcell
Can Nscoding and Codable Co-Exist
How to Make High Score of Game to Be Saved on Leaderboard, with Swift
Struggling with Notificationcenter/Combine in Swiftui/Avplayer