我的代码如下。我已经添加了行号以便于参考。
我没有得到的是第32行失败,错误是"带有基本类型' [字符]'的不明确的下标。和索引类型' CountableClosedRange'",但第12,16和20行工作正常。
1 import Foundation
2
3 struct PhoneNumber: CustomStringConvertible {
4 var parsed: [ Character ]
5 let badNum: [ Character ] = Array( "0000000000" )
6
7 var number: String {
8 return String( parsed )
9 }
10
11 var areaCode: String {
12 return String( parsed[ 0...2 ] ) // fine
13 }
14
15 var exchange: String {
16 return String( parsed[ 3...5 ] ) // fine
17 }
18
19 var subscriber: String {
20 return String( parsed[ 6...9 ] ) // fine
21 }
22
23 var description: String {
24 return "(\( areaCode )) \( exchange )-\( subscriber )"
25 }
26
27 init( _ startingNumber: String ) {
28 parsed = Array( startingNumber.components( separatedBy:
29 CharacterSet.decimalDigits.inverted ).joined() )
30
31 if parsed.count == 11 && parsed[ 0 ] == "1" {
32 // parsed = parsed[ 1...9 ] // This Fails with error: ambiguous subscript with base type '[Character]' and index type 'CountableClosedRange<Int>'
33
34 parsed.remove( at: 0 ) // This Works fine
35 } else if parsed.count != 10 {
36 parsed = badNum
37 }
38 }
39 }
40
41 print( PhoneNumber( "+1.703.283.7360" ) )