Swift 4.2, String firstIndex() function error in Xcode playground
You can try index(of
let index = greeting.index(of: ",") ?? greeting.endIndex
as firstIndex
exists in Xcode 10 beta Doc
Is Nil-Coalescing always needed when using firstIndex(of: Character) in Swift?
Consider this example.
let greeting = "Hey There!"
let index = greeting.firstIndex(of: ",")
index
is of type Index?
, so it can be nil. Since the string has no ',', the value of index is nil.
So this code becomes illegal. Since index cannot be an optional value.
let beginning = greeting[..<index]
You can alternatively unwrap it and get the index if it is valid index like this.
guard let indexFound = index else {
print("Character not) found in string"
return
}
let beginning = greeting[..<indexFound]
print("The first occurance of the character is at \(beginning).")
Real world example: (I know it's not good, but it should be enough :x)
Remember the bot captcha's that pop up in websites? The ones that ask
you to identify the number of cars, street signs etc. So there you
click on the boxes which show the requirement. and click 'submit'. But
if there aren't any, you click 'Skip'. So drawing parallels. If you
have a valid index, it returns the valid index, otherwise it return
nil
which is not an validIndex
, but it is a valid answer to the
question asked. (Is there a ',' inside the string?) The problem here is, the next part. Slicing an array requires you to have a validIndex
, so yourindex
currently is an optional which you can change to a valid index by safely unwrapping like my example or having a nil-coalescing check at the time of getting the index.
You should look up optionals in Swift to get a better understanding.
Why does print(date object) show a different date than what the value actually is?
The local time zone in Norway on May 5th at 0:00
is UTC+0100.
However print()
displays dates always in UTC(+0000) which is May 4th at 23:00
.
Replace
print(myDate)
with
print(myDate.description(with: .current))
to get the local date and time
Swift playground and LeetCode OJ
Try this:
class Solution {
func reverseString(s: String) -> String {
let rev = String(s.characters.reverse())
print(rev)
return rev
}
}
var str = Solution()
str.reverseString("Hello")
If you intend to add custom methods which works on a a particular Type
than create an extension on that Type type.
extension String {
// you methods
}
For example:
extension String {
func length() -> Int {
return self.characters.count
}
}
Then you can use it as class function on String type
let greetings: String = "Hello"
greetings.length() // 5
Substring of string reuses storage of original string?
The behavior is correct.
The substring shares the reference counter of the original string. If the original string is destroyed the reference is still alive.
Please watch WWDC 2017: What's new in Swift from 36:00
And actually even the quoted text confirms that behavior because it says that after slicing a string the entire string is kept in memory.
Why does String.subscript(_:) require the types `String.Index` and `Int` to be equal when there is no `Int` involved?
The current version of Swift works with the Substring
struct which is a sliced String
.
The error seems to be misleading and occurs if you are going to assign a (range-subscripted) Substring
to a String
variable.
To fix the error create a String
from the Substring
iteration.template = String(template[iterationSubstring.endIndex...substring.startIndex])
Nevertheless you are strongly discouraged from creating ranges with indices from different strings (iterationSubstring
and substring
). Slice the main string, the indices are preserved.
The crash in the second (meanwhile deleted) example occurred because the last character of a string is at index before endIndex
, it's
template[template.startIndex..<template.endIndex]
or shorter
template[template.startIndex...]
Xcode 13.3 magically changing a function call into a property access
I had the same problem with Xcode 13.3 and I don't know what is causing that. But I found a solution that worked for me and made possible to build the application without further problems.
Just remove the ! from de method's call and use == false instead as follows:
if let state = ...,
let field = state....,
field.xxxxasdfxxxx == false {
Why does map(_:) in Swift Playground return a String and not a tuple?
Get Index of Orders that matches Goods
To get index & element:
var r = orders.enumerated().map { ( index, element) -> (Int, Int) in
return (index, element)
}.filter { (index, element) -> Bool in
if element == goods {
return true
}
return false
}
or more compact:
var r = orders.enumerated().map { index, element in (index, element) }
.filter { _, element in element == goods ? true : false }
print("r: \(r.first)")
Prints:
r: (1, 2)
If you really want to find the first match only, a for loop is more efficient, as you can break
after the first match is found.
Playground
What you see "(0, 2)\n"
is the result of print
. What it prints out in console is (0, 2)
plus newline.
If you want to see the actual value of r.first!
in the sidebar, remove the print:
print (r.first!)
r.first!
Result:
Related Topics
Cloudkit - "Invalid Bundle Id for Container"
Generics and Functional Programming in Swift
How to Replicate Hash_Hmac('Sha256', $Key, $Secret_Key) Function in Swift 4
How to Place Uisearchcontroller to the Navigationtitle and How to Enable and Disable It by Button
Instance Member Cannot Be Used on Type | Closures
How to Pass a Nil Value for One of the Parameter in Alamofire Post Request
How to Remove Space Above and Below Text View in Swiftui
Swiftui List View Not Updating After Core Data Entity Updated in Another View
How Does Appdelegate.Swift Replace Appdelegate.H and Appdelegate.M in Xcode 6.3
Rotate a Sprite to Sprite Position Not Exact in Spritekit with Swift
Perform Migration by Adding List() and Another Model Class
How to Incorporate Swift Package Manager to an Existing Xcode Project
How to Use Spritekit Archives with Skspritenode Subclasses
Swift 4: Validating Credit Card Expiration Date
Delegate Must Respond to Locationmanager:Didupdatelocations Swift Eroor