代码之家  ›  专栏  ›  技术社区  ›  Omega_Pixel

如何在Swift中使用do catch函数

  •  0
  • Omega_Pixel  · 技术社区  · 3 年前

    我是一个快速和iOS开发的新手,我遇到了一个奇怪的情况。

    我试图使用do-catch语句来防止错误,但似乎do-catch什么都没做。

    这是我的代码:

    extension String {
        mutating func insert(string: String, ind: Int) {
            do { 
                try self.insert(contentsOf: string, at: self.index(self.startIndex, offsetBy: ind))
            // This do-catch is to make sure nothing happens if there is no √ in the equation.
            } catch {
              
            }
        }
    }
    

    “尝试”的声明似乎也没有起到任何作用!我在网上论坛上搜索了又搜索,没有找到任何有用的东西。

    我对Java很了解,你总能发现一个特定的错误,比如:

    try {
    
    } catch NameOfException {
    
    }
    

    但我在斯威夫特身上找不到类似的东西。返回的错误代码如下:

    Swift/StringCharacterView.swift:60: Fatal error: String index is out of bounds
    2022-03-19 17:37:04.234797-0600 iOS-App[18937:2984774] Swift/StringCharacterView.swift:60: Fatal error: String index is out of bounds
    (lldb) 
    

    我认为这意味着 String 索引显然是不受限制的,但我找不到一个方法(比如Java)来捕捉这种表达式,或者我甚至无法处理Java之类的错误。但我想抓住它,这样我的应用程序就不会崩溃。

    我正在使用一个函数来尝试定位 一串 ; myString.insert() ind是 Index 插入提供的 一串 价值

    2 回复  |  直到 3 年前
        1
  •  0
  •   Leo Dabus    3 年前

    您可以将抛出添加到方法签名中,然后抛出一个自定义错误。我还将使该方法通用并扩展 StringProtocol 而不是 String 支持 Substring 也请注意,约束到 RangeReplaceableCollection 需要能够使用 mutating func insert<S>(contentsOf newElements: S, at i: Index) where S: Collection, Element == S.Element :

    extension String {
        enum Error: Swift.Error {
            case invalidIndexDistance
        }
    }
    

    extension StringProtocol where Self: RangeReplaceableCollection {
        mutating func insert<S: StringProtocol>(contentsOf string: S, at distance: Int) throws {
            guard let index = self.index(startIndex, offsetBy: distance, limitedBy: endIndex) else {
                throw String.Error.invalidIndexDistance
            }
            insert(contentsOf: string, at: index)
        }
    }
    

    var substring = "abcde".dropFirst()
    do {
        try substring.insert(contentsOf: "fgh", at: 2)
        substring  // "bcfghde"
    } catch {
        print(error)
    }
    
        2
  •  0
  •   Leo Dabus    3 年前

    我找到了一种相对肮脏的方法来修复未经处理的错误,比如@Alexander said。

    extension String {
        mutating func insert(sourceString: String, string: String, ind: Int) {
            do {
                if ind > sourceString.count {
                  
                } else {
                    try insert(contentsOf: string, at: index(startIndex, offsetBy: ind))
                }
            // This do-catch is to make sure nothing happens if there is no √ in the equation.
            } catch GenericError.StringException {
              
            }
        }
    }
    

    谢谢你们的帮助!