2016-11-09 28 views
7

Tôi gặp lỗi ở dòng cuối cùng khi tôi cố gắng đặt label1 thành chữ cái đầu tiên của string, sử dụng phiên bản mới nhất của Swift. Giải quyết vấn đề này như thế nào?Chuỗi có thể không được lập chỉ mục với int

let preferences = UserDefaults.standard 
let name1 = "" + preferences.string(forKey: "name")! 
let name2 = name1 
label1.text = name2.substring(from: 0) 
+1

Xem [H ow String.Index làm việc trong Swift 3] (http://stackoverflow.com/questions/39676939/how-does-string-index-work-in-swift-3) và [String chuỗi hoạt động như thế nào trong Swift 3] (http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3) – Hamish

Trả lời

0

Yêu cầu chỉ mục chứ không phải là Int.

let str = "string" 
print(str.substring(from: str.startIndex)) 
11

Đó là bởi vì substring phương pháp chấp nhận String.Index thay vì đơn giản Int. Hãy thử điều này thay vì:

let index = name2.index(str.startIndex, offsetBy: 0) //replace 0 with index to start from 
label.text = name2.substring(from: index) 
1

chữ cái đầu tiên của chuỗi trong Swift 3 là

label1.text = String(name2[name2.startIndex]) 

String không thể được lập chỉ mục bởi Int đã có trong Swift 2

0

Dưới đây là một vài chức năng làm cho nó có mục tiêu-c như

func substringOfString(_ s: String, toIndex anIndex: Int) -> String 
{ 
    return s.substring(to: s.index(s.startIndex, offsetBy: anIndex)) 
} 


func substringOfString(_ s: String, fromIndex anIndex: Int) -> String 
{ 
    return s.substring(from: s.index(s.startIndex, offsetBy: anIndex)) 
} 


//examples 
let str = "Swift's String implementation is completely and utterly irritating" 
let newstr = substringOfString(str, fromIndex: 30) // is completely and utterly irritating 
let anotherStr = substringOfString(str, toIndex: 14) // Swift's String 
let thisString = substringOfString(anotherStr, toIndex: 5) // Swift 
Các vấn đề liên quan