StringIndex advance method fails to compile

Asked 1 years ago, Updated 1 years ago, 114 views

 // Load Foundation Framework
import Foundation

var str = "New power of String!"

// substringFromIndex cannot be used without Foundation
become str.substringFromIndex(advance(str.startIndex,4))) // "power of String!"

It will not be "power of string".
Advance will display an error.I tried to google, but I didn't get a proper answer.
I don't know what to do, thank you.

swift swift3

2022-09-30 21:22

1 Answers

The posting code appears to be based on Swift2 or earlier formatting.In Swift3, it's written like this.

import Foundation

var str = "New power of String!"
let newString=str.substring(from:str.index(str.startIndex, offsetBy:4))
print(newString)
// Output: power of String!

In the transition from Swift2 to Swift3, changes in the format of functions and methods tend to move the FromIndex portion of the method name, for example, substringFromIndex, to the label of the argument.There is also a tendency to reduce the number of independent functions and migrate to methods.The independent function advance has changed to the method index(_i:String.Index, offsetByn:String.IndexDistance).

Swift.org
According to information directly from Swift developers, Swift 4 is scheduled to be released around this fall, and Swift's grammar changes are not likely to end yet.In particular, the String type is expected to undergo major changes.As you can see in this example, having to write str. three times to write a single line of code that takes out the 5th character of the string is far from the word sophisticated, and I would rather you do something about it.
It's impossible to limit the information to Japanese under a changing situation.It's best to get direct information from Apple and Swift developers, and it's better to think that English isn't the time to avoid it.
Also, consider using Xcode8's conversion capability to rewrite Swift2 code to Swift3.Bulk conversion is available from the Edit menu > Convert > Edit Current Swift Syntax...The conversion was not successful with this code, and although it is not perfect, I feel that I can expect about 80% of the time.


2022-09-30 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.