2016-11-09 5 views
7

ile dizine eklenemedi En son Swift sürümünü kullanarak label1 ilk harfini string ayarlamaya çalıştığımda son satırda hata alıyorum. bu sorunu nasıl çözeriz?Dize, int

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

Bkz. [H ow, String.Index, Swift 3'te çalışır (http://stackoverflow.com/questions/39676939/how-does-string-index-work-in-swift-3) ve [String 3'te Swift dizisi nasıl çalışır?] (http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3) – Hamish

cevap

0

Int değil, bir Dizin soruyor. substring yöntem yerine düz Int ait String.Index kabul ettiğinden var

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

. Bunun yerine bu deneyin:

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

Swift 3'te dize ilk harfi Dize zaten

0

İşte Swift 2'de Int tarafından dizine edilemedi

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

olan fonksiyonları bir çift var Bu, daha fazla objektif hale getiriyor

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