2016-11-16 165 views
2

我有下面的类,它包含字符串的私有结构,我想稍后将它们用于格式化的字符串。但是,代码在运行时崩溃。在Swift中用%@格式化字符串

这是为什么?是因为它被定义为静态的让?

下面是剥离代码:

class LGNotificationHandler { 
    private struct Strings { 
     static let SentImagesENG = "Sent %@ images to the event" 
     static let SentImagesTUR = "Etkinliğe %@ görsel gönderdi" 
    } 

    func buildNotificationString(imageCount: Int) -> String { 
     if imageCount == 1 { 
     . 
     . 
     . 

     } else { 
      // below line is giving error at run time 
      notificationENG = String(format: Strings.SentImagesENG, imageCount) 
      notificationTUR = String(format: Strings.SentImagesTUR, imageCount) 
     } 
    } 
} 
+0

哪条线路导致崩溃?什么是从崩溃错误信息? – rmaddy

+0

以'notificationENG ='开头的行会给出错误。我在最后的评论中提到了这一点。为了更好的可视性,我会把它放在线上。我得到的错误是线程20:EXC_BAD_ACCESS(code = 1,address = 0x2) – oyalhi

回答

7

你忽略了提供有关崩溃的,但一个明显的问题的任何细节与使用%@格式说明的Int。您需要使用%dInt

+0

实际上,'%@'是用于对象的,而不仅仅是文本。您可以在文档中找到有关所有格式说明符的详细信息。查看关于'NSString stringWithFormat:'的文档以获取链接。 – rmaddy

+1

其实,这里的链接:https://developer.apple.com/library/prerelease/content/documentation/CoreFoundation/Conceptual/CFStrings/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265 – rmaddy

6

您需要%d更换%@。 ImageCount是Int的值。所以请使用%d而不是%@

格式说明:

%d - int Value 
%f - float value 
%ld - long value 
%@ - string value and for many more. 

对于看到所有的格式说明见苹果文档Format Specifiers