【问题标题】:String may not be indexed with int字符串不能用 int 索引
【发布时间】:2016-11-09 16:14:02
【问题描述】:

当我尝试使用最新版本的 Swift 将 label1 设置为 string 的第一个字母时,最后一行出现错误。如何解决这个问题?

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

【问题讨论】:

标签: ios swift3


【解决方案1】:

这是因为substring 方法接受String.Index 而不是普通的Int。试试这个:

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

【讨论】:

    【解决方案2】:

    在 Swift 3 中字符串的第一个字母

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

    字符串不能被 Swift 2 中的Int 索引

    【讨论】:

      【解决方案3】:

      它要求一个索引,而不是一个整数。

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

      【讨论】:

        【解决方案4】:

        这里有几个函数使它更像objective-c

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-12
          • 2021-01-01
          • 1970-01-01
          • 2015-01-05
          • 2019-08-12
          • 2016-07-30
          • 1970-01-01
          • 2017-06-30
          相关资源
          最近更新 更多