Cannot invoke initializer for type 'Range' with an argument list of type '(Range)'

后端 未结 4 1192
谎友^
谎友^ 2020-11-28 10:55

After updating to Xcode 10 beta, which apparently comes with Swift 4.1.50, I\'m seeing the following error which I\'m not sure how to fix:

Cannot invo

4条回答
  •  被撕碎了的回忆
    2020-11-28 11:57

    Some background:

    In Swift 3, additional range types were introduced, making a total of four (see for example Ole Begemann: Ranges in Swift 3):

    Range, ClosedRange, CountableRange, CountableClosedRange
    

    With the implementation of SE-0143 Conditional conformances in Swift 4.2, the “countable” variants are not separate types anymore, but (constrained) type aliases, for example

     public typealias CountableRange = Range
          where Bound.Stride : SignedInteger
    

    and, as a consequence, various conversions between the different range types have been removed, such as the

    init(_ other: Range)
    

    initializer of struct Range. All theses changes are part of the [stdlib][WIP] Eliminate (Closed)CountableRange using conditional conformance (#13342) commit.

    So that is the reason why

    let range: Range = Range(start..

    does not compile anymore.

    How to fix

    As you already figured out, this can be simply fixed as

    let range: Range = start..

    or just

    let range = start..

    without the type annotation.

    Another option is to use a one sided range (introduced in Swift 4 with SE-0172 One-sided Ranges):

    extension String {
        func index(of aString: String, startingFrom position: Int = 0) -> String.Index? {
            let start = index(startIndex, offsetBy: position)
            return self[start...].range(of: aString, options: .literal)?.lowerBound
        }
    }
    

    This works because the substring self[start...] shares its indices with the originating string self.

提交回复
热议问题