How do I find the last occurrence of a substring in a Swift string?

前端 未结 4 859
夕颜
夕颜 2020-12-07 00:30

In Objective-C I used:

[@\"abc def ghi abc def ghi\" rangeOfString:@\"c\" options:NSBackwardsSearch];

But now NSBackWardsSearch seems not

4条回答
  •  庸人自扰
    2020-12-07 01:05

    Cocoa frameworks should be accessible in Swift, but you need to import them. Try importing Foundation to access the NSString API. From "Working with Cocoa Data Types–Strings" of the "Using Swift with Cocoa and Objective-C" guide:

    Swift automatically bridges between the String type and the NSString class. [...] To enable string bridging, just import Foundation.

    Additionally, NSBackwardsSearch is an enum value (marked & imported as an option), so you have to use Swift's enum/option syntax to access it (as part of the NSStringCompareOptions option type). Prefixes are stripped from C enumeration values, so drop the NS from the value name.

    Taken all together, we have:

    import Foundation
    "abc def ghi abc def ghi".rangeOfString("c", options:NSStringCompareOptions.BackwardsSearch)
    

    Note that you might have to use the distance and advance functions to properly make use of the range from rangeOfString.

提交回复
热议问题