diff --git a/EnzevalosContact+CoreDataClass.swift b/EnzevalosContact+CoreDataClass.swift
index 003e2e90f14b20d129c4351154b5fb20e300a8b6..3edb8959f8c5559504e399f05a260846c873fa0c 100644
--- a/EnzevalosContact+CoreDataClass.swift
+++ b/EnzevalosContact+CoreDataClass.swift
@@ -11,18 +11,31 @@ import Foundation
 import CoreData
 import UIKit
 import Contacts
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l < r
+  case (nil, _?):
+    return true
+  default:
+    return false
+  }
+}
+
 
 @objc(EnzevalosContact)
-public class EnzevalosContact: NSManagedObject, Contact, Comparable {
+open class EnzevalosContact: NSManagedObject, Contact, Comparable {
         
-    public var name:String{
+    open var name:String{
         get{
             return getName()
         }
     }
     
     
-    public var to: [Mail]{
+    open var to: [Mail]{
         get{
             var mails = [Mail]()
             if let adrs = addresses{
@@ -39,7 +52,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         }
     }
     
-    public var bcc: [Mail]{
+    open var bcc: [Mail]{
         get{
             var mails = [Mail]()
             if let adrs = addresses{
@@ -58,7 +71,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
     
     
     
-    public var cc: [Mail]{
+    open var cc: [Mail]{
         get{
             var mails = [Mail]()
             if let adrs = addresses{
@@ -75,7 +88,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         }
     }
     
-    public var from: [Mail]{
+    open var from: [Mail]{
         get{
             var mails = [Mail]()
             if let adrs = addresses{
@@ -92,7 +105,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         }
     }
     
-    public var records: [KeyRecord] {
+    open var records: [KeyRecord] {
         get{
             var myrecords = [KeyRecord]()
             for r in DataHandler.handler.receiverRecords{
@@ -105,7 +118,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         }
     
     }
-    public var hasKey: Bool{
+    open var hasKey: Bool{
         get {
             for item in addresses!{
                 let adr = item as! MailAddress
@@ -117,7 +130,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         }
     }
     
-    public var cnContact: CNContact?{
+    open var cnContact: CNContact?{
         get{
             let contactFromBook = AddressHandler.findContact(self)
             if contactFromBook.count > 0 {
@@ -129,7 +142,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
             let con = CNMutableContact()
             let name = self.displayname
             if let n = name {
-                let nameArray = n.characters.split(" ").map(String.init)
+                let nameArray = n.characters.split(separator: " ").map(String.init)
                 switch nameArray.count {
                 case 1:
                     con.givenName = nameArray.first!
@@ -178,7 +191,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         return name
     }
     
-    func getAddress(address: String)-> Mail_Address?{
+    func getAddress(_ address: String)-> Mail_Address?{
         var addr: Mail_Address
         if addresses != nil {
             for obj in addresses! {
@@ -191,11 +204,11 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
         return nil
     }
     
-    func getAddressByMCOAddress(mcoaddress: MCOAddress)-> Mail_Address?{
+    func getAddressByMCOAddress(_ mcoaddress: MCOAddress)-> Mail_Address?{
         return getAddress(mcoaddress.mailbox!)
     }
     
-    public func getMailAddresses()->[MailAddress]{
+    open func getMailAddresses()->[MailAddress]{
         var adr = [MailAddress] ()
         if self.addresses != nil {
             for a in addresses!{
@@ -207,7 +220,7 @@ public class EnzevalosContact: NSManagedObject, Contact, Comparable {
     }
 }
 
-private func isEmpty(contact: EnzevalosContact)-> Bool{
+private func isEmpty(_ contact: EnzevalosContact)-> Bool{
     let mails = contact.from
         if(mails.count == 0){
             return true
diff --git a/Mail+CoreDataClass.swift b/Mail+CoreDataClass.swift
index e5f9dfb52f4d20a8e46904118bec2f8c4141e734..524dc4add3159df7407058a360d9df76b11c89c6 100644
--- a/Mail+CoreDataClass.swift
+++ b/Mail+CoreDataClass.swift
@@ -12,7 +12,7 @@ import Foundation
 import CoreData
 
 @objc(Mail)
-public class Mail: NSManagedObject, Comparable {
+open class Mail: NSManagedObject, Comparable {
 
     var showMessage: Bool = false
 
@@ -22,14 +22,14 @@ public class Mail: NSManagedObject, Comparable {
 
     var isRead: Bool {
         get {
-            let value = flag.contains(MCOMessageFlag.Seen)
+            let value = flag.contains(MCOMessageFlag.seen)
             return value
         }
         set {
             if !newValue {
-                flag.remove(MCOMessageFlag.Seen)
+                flag.remove(MCOMessageFlag.seen)
             } else {
-                flag.insert(MCOMessageFlag.Seen)
+                flag.insert(MCOMessageFlag.seen)
             }
             DataHandler.handler.save()
         }
@@ -37,25 +37,25 @@ public class Mail: NSManagedObject, Comparable {
 
     var timeString: String {
         var returnString = ""
-        let dateFormatter = NSDateFormatter()
-        dateFormatter.locale = NSLocale.currentLocale()
+        let dateFormatter = DateFormatter()
+        dateFormatter.locale = Locale.current
         let mailTime = self.date
-        let interval = NSDate().timeIntervalSinceDate(mailTime)
+        let interval = Date().timeIntervalSince(mailTime as Date)
         switch interval {
         case -55..<55:
             returnString = NSLocalizedString("Now", comment: "New email")
         case 55..<120:
             returnString = NSLocalizedString("OneMinuteAgo", comment: "Email came one minute ago")
         case 120..<24 * 60 * 60:
-            dateFormatter.timeStyle = .ShortStyle
-            returnString = dateFormatter.stringFromDate(mailTime)
+            dateFormatter.timeStyle = .short
+            returnString = dateFormatter.string(from: mailTime as Date)
         case 24 * 60 * 60..<48 * 60 * 60:
             returnString = NSLocalizedString("Yesterday", comment: "Email came yesterday")
         case 48 * 60 * 60..<72 * 60 * 60:
             returnString = NSLocalizedString("TwoDaysAgo", comment: "Email came two days ago")
         default:
-            dateFormatter.dateStyle = .ShortStyle
-            returnString = dateFormatter.stringFromDate(mailTime)
+            dateFormatter.dateStyle = .short
+            returnString = dateFormatter.string(from: mailTime as Date)
         }
         return returnString
     }
@@ -69,12 +69,12 @@ public class Mail: NSManagedObject, Comparable {
         }
 
         if message != nil {
-            message = message!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
+            message = message!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
             if message!.characters.count > 50 {
-                message = message!.substringToIndex(message!.startIndex.advancedBy(50))
+                message = message!.substring(to: message!.characters.index(message!.startIndex, offsetBy: 50))
             }
-            let messageArray = message!.componentsSeparatedByString("\n")
-            return messageArray.joinWithSeparator(" ")
+            let messageArray = message!.components(separatedBy: "\n")
+            return messageArray.joined(separator: " ")
         } else {
             return nil
         }
@@ -159,19 +159,19 @@ public class Mail: NSManagedObject, Comparable {
             subj = subject!
         }
         if self.trouble {
-            returnString.appendContentsOf("❗️ ")
+            returnString.append("❗️ ")
         }
         if !self.isRead {
-            returnString.appendContentsOf("🔵 ")
+            returnString.append("🔵 ")
         }
-        if MCOMessageFlag.Answered.isSubsetOf(flag) {
-            returnString.appendContentsOf("↩️ ")
+        if MCOMessageFlag.answered.isSubset(of: flag) {
+            returnString.append("↩️ ")
         }
-        if MCOMessageFlag.Forwarded.isSubsetOf(flag) {
-            returnString.appendContentsOf("➡️ ")
+        if MCOMessageFlag.forwarded.isSubset(of: flag) {
+            returnString.append("➡️ ")
         }
-        if MCOMessageFlag.Flagged.isSubsetOf(flag) {
-            returnString.appendContentsOf("⭐️ ")
+        if MCOMessageFlag.flagged.isSubset(of: flag) {
+            returnString.append("⭐️ ")
         }
         return "\(returnString)\(subj)"
     }
diff --git a/enzevalos_iphone.xcodeproj/project.pbxproj b/enzevalos_iphone.xcodeproj/project.pbxproj
index ab0361dd7ff1b60d11e58e0233dd75052c683501..b2fbbd2a7b72e5a4601fc8995fe4ba07efba7725 100644
--- a/enzevalos_iphone.xcodeproj/project.pbxproj
+++ b/enzevalos_iphone.xcodeproj/project.pbxproj
@@ -765,7 +765,7 @@
 					A13526741D955BDF00D3BFE1 = {
 						CreatedOnToolsVersion = 7.3.1;
 						DevelopmentTeam = 4377G946WP;
-						LastSwiftMigration = 0800;
+						LastSwiftMigration = 0820;
 						SystemCapabilities = {
 							com.apple.Keychain = {
 								enabled = 1;
@@ -775,11 +775,13 @@
 					A135268B1D955BE000D3BFE1 = {
 						CreatedOnToolsVersion = 7.3.1;
 						DevelopmentTeam = 4377G946WP;
+						LastSwiftMigration = 0820;
 						TestTargetID = A13526741D955BDF00D3BFE1;
 					};
 					A13526961D955BE000D3BFE1 = {
 						CreatedOnToolsVersion = 7.3.1;
 						DevelopmentTeam = 4377G946WP;
+						LastSwiftMigration = 0820;
 						TestTargetID = A13526741D955BDF00D3BFE1;
 					};
 				};
@@ -876,7 +878,7 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n    # print error to STDERR\n    echo \"error: The sandbox is not in sync with the Podfile.lock. Run \'pod install\' or update your CocoaPods installation.\" >&2\n    exit 1\nfi\n";
+			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n    cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n    exit 1\nfi\n";
 			showEnvVarsInLog = 0;
 		};
 		6C4CB727DDC2AC31CCE50B26 /* [CP] Embed Pods Frameworks */ = {
@@ -921,7 +923,7 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n    # print error to STDERR\n    echo \"error: The sandbox is not in sync with the Podfile.lock. Run \'pod install\' or update your CocoaPods installation.\" >&2\n    exit 1\nfi\n";
+			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n    cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n    exit 1\nfi\n";
 			showEnvVarsInLog = 0;
 		};
 		D6F0EB205D61EA8C8A045390 /* [CP] Check Pods Manifest.lock */ = {
@@ -936,7 +938,7 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n    # print error to STDERR\n    echo \"error: The sandbox is not in sync with the Podfile.lock. Run \'pod install\' or update your CocoaPods installation.\" >&2\n    exit 1\nfi\n";
+			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n    cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n    exit 1\nfi\n";
 			showEnvVarsInLog = 0;
 		};
 		E98D3D9213C0A8CF7EDD28B1 /* [CP] Copy Pods Resources */ = {
@@ -1223,6 +1225,7 @@
 				ONLY_ACTIVE_ARCH = YES;
 				SDKROOT = iphoneos;
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = "";
 			};
 			name = Debug;
 		};
@@ -1265,6 +1268,7 @@
 				MTL_ENABLE_DEBUG_INFO = NO;
 				SDKROOT = iphoneos;
 				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = "";
 				VALIDATE_PRODUCT = YES;
 			};
 			name = Release;
@@ -1314,7 +1318,7 @@
 				SWIFT_OBJC_BRIDGING_HEADER = "enzevalos_iphone-Bridging-Header.h";
 				"SWIFT_OBJC_BRIDGING_HEADER[arch=*]" = "enzevalos_iphone/enzevalos_iphone-Bridging-Header.h";
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 			};
 			name = Debug;
 		};
@@ -1362,7 +1366,7 @@
 				PROVISIONING_PROFILE = "";
 				SWIFT_OBJC_BRIDGING_HEADER = "enzevalos_iphone-Bridging-Header.h";
 				"SWIFT_OBJC_BRIDGING_HEADER[sdk=*]" = "enzevalos_iphone/enzevalos_iphone-Bridging-Header.h";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 			};
 			name = Release;
 		};
@@ -1375,7 +1379,7 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				PRODUCT_BUNDLE_IDENTIFIER = "fu-berlin.enzevalos-iphoneTests";
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/enzevalos_iphone.app/enzevalos_iphone";
 			};
 			name = Debug;
@@ -1389,7 +1393,7 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				PRODUCT_BUNDLE_IDENTIFIER = "fu-berlin.enzevalos-iphoneTests";
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/enzevalos_iphone.app/enzevalos_iphone";
 			};
 			name = Release;
@@ -1402,7 +1406,7 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				PRODUCT_BUNDLE_IDENTIFIER = "fu-berlin.enzevalos-iphoneUITests";
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 				TEST_TARGET_NAME = enzevalos_iphone;
 			};
 			name = Debug;
@@ -1415,7 +1419,7 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				PRODUCT_BUNDLE_IDENTIFIER = "fu-berlin.enzevalos-iphoneUITests";
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SWIFT_VERSION = 2.3;
+				SWIFT_VERSION = 3.0;
 				TEST_TARGET_NAME = enzevalos_iphone;
 			};
 			name = Release;
diff --git a/enzevalos_iphone.xcodeproj/xcuserdata/jakobsbode.xcuserdatad/xcschemes/enzevalos_iphone.xcscheme b/enzevalos_iphone.xcodeproj/xcuserdata/jakobsbode.xcuserdatad/xcschemes/enzevalos_iphone.xcscheme
index 05cdde31c07861b6eb53d881f79ab9beb5201ed2..17db2fbcbb129b11ccc16927e2dda9ed0119eeca 100644
--- a/enzevalos_iphone.xcodeproj/xcuserdata/jakobsbode.xcuserdatad/xcschemes/enzevalos_iphone.xcscheme
+++ b/enzevalos_iphone.xcodeproj/xcuserdata/jakobsbode.xcuserdatad/xcschemes/enzevalos_iphone.xcscheme
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0810"
+   LastUpgradeVersion = "0820"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"
diff --git a/enzevalos_iphone/AddressHandler.swift b/enzevalos_iphone/AddressHandler.swift
index db8e871644f819ca531716ffa832064d9718721a..99adf1f673f2f29bfd03bb2422f7b1553bf1dc01 100644
--- a/enzevalos_iphone/AddressHandler.swift
+++ b/enzevalos_iphone/AddressHandler.swift
@@ -12,18 +12,18 @@ import UIKit.UIImage
 
 class AddressHandler {
     
-    static var addresses : [String] = []
+    static var addresses: [String] = []
     
-    static var freqAlgorithm : [String] -> [(UIImage, String, String, UIImage?, UIColor)] = {
+    static var freqAlgorithm: ([String]) -> [(UIImage, String, String, UIImage?, UIColor)] = {
         (inserted : [String]) -> [(UIImage, String, String, UIImage?, UIColor)] in
         var cons : [(UIImage,String,String,UIImage?,UIColor)] = []
             do{
                 
-                try AppDelegate.getAppDelegate().contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName), CNContactEmailAddressesKey, CNContactImageDataKey, CNContactThumbnailImageDataKey]), usingBlock: {
-                    ( c : CNContact, let stop) -> Void in
+                try AppDelegate.getAppDelegate().contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: CNContactFormatterStyle.fullName), CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor]), usingBlock: {
+                    ( c : CNContact, stop) -> Void in
 //                    print(c)
                     for email in c.emailAddresses {
-                        let addr = email.value as! String
+                        let addr = email.value as String
                         var type : UIImage? = nil
                         if c.emailAddresses.count > 1 {
                             if email.label == "_$!<Work>!$_"{
@@ -38,13 +38,13 @@ class AddressHandler {
                         }
                         var color = c.getColor()
                         if c.thumbnailImageData != nil {
-                            color = UIColor.grayColor() //blackColor()
+                            color = UIColor.gray //blackColor()
                         }
                         if addr == "" {
                             continue
                         }
-                        if !inserted.contains(addr.lowercaseString) {
-                            if let name = CNContactFormatter.stringFromContact(c, style: .FullName) {
+                        if !inserted.contains(addr.lowercased()) {
+                            if let name = CNContactFormatter.string(from: c, style: .fullName) {
                                     cons.append((c.getImageOrDefault(), name, addr, type, color))
                             }
                             else {
@@ -55,7 +55,7 @@ class AddressHandler {
                     })
             }
             catch {}
-        var list : [(UIImage,String,String,UIImage?,UIColor)] = []
+        var list: [(UIImage,String,String,UIImage?,UIColor)] = []
         var entrys = CollectionDataDelegate.maxFrequent
         if cons.count < entrys {
             entrys = cons.count
@@ -67,33 +67,33 @@ class AddressHandler {
             //let index = abs(Int(arc4random())) % cons.count
             let index = i % cons.count
             list.append(cons[index])
-            cons.removeAtIndex(index)
+            cons.remove(at: index)
         }
         
         return list
     }
     
-    static func proveAddress(s : NSString) -> Bool {
-        if addresses.contains((s as String).lowercaseString){
+    static func proveAddress(_ s: NSString) -> Bool {
+        if addresses.contains((s as String).lowercased()){
             return true
         }
-        return EnzevalosEncryptionHandler.hasKey(DataHandler.handler.getContactByAddress((s as String).lowercaseString))//KeyHandler.getHandler().addrHasKey(s as String)//inContacts(s as String)
+        return EnzevalosEncryptionHandler.hasKey(DataHandler.handler.getContactByAddress((s as String).lowercased()))//KeyHandler.getHandler().addrHasKey(s as String)//inContacts(s as String)
         //return false
     }
     
-    static func inContacts( name : String) -> Bool{
+    static func inContacts(_ name: String) -> Bool{
         AppDelegate.getAppDelegate().requestForAccess({access in
             print(access)
         })
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName(name), keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey])
+                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: CNContact.predicateForContacts(matchingName: name), keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor])
                 for con in conList {
                     print(con.givenName)
                     print(con.familyName)
                     
-                    if (con.givenName+con.familyName).stringByReplacingOccurrencesOfString(" ", withString: "") == name.stringByReplacingOccurrencesOfString(" ", withString: ""){
+                    if (con.givenName+con.familyName).replacingOccurrences(of: " ", with: "") == name.replacingOccurrences(of: " ", with: ""){
                         return true
                     }
                 }
@@ -112,12 +112,12 @@ class AddressHandler {
     
     
     
-    static func getContact(name : String) -> [CNContact]{
+    static func getContact(_ name: String) -> [CNContact]{
         AppDelegate.getAppDelegate().requestForAccess({access in})
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName(name), keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactImageDataKey, CNContactThumbnailImageDataKey])
+                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: CNContact.predicateForContacts(matchingName: name), keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor])
                 return conList
             }
             catch {
@@ -132,13 +132,13 @@ class AddressHandler {
     }
     
     
-    static func getContactByID(identifier : String) -> [CNContact]{
+    static func getContactByID(_ identifier: String) -> [CNContact]{
         AppDelegate.getAppDelegate().requestForAccess({access in})
         let ids = [identifier]
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(CNContact.predicateForContactsWithIdentifiers(ids), keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactImageDataKey, CNContactThumbnailImageDataKey])
+                let conList = try AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: CNContact.predicateForContacts(withIdentifiers: ids), keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor])
                 return conList
             }
             catch {
@@ -153,11 +153,11 @@ class AddressHandler {
     }
 
     /*          [insertedEmail] -> [(contactImage, name, address, emailLabelImage, backgroundcolor)] */
-    static func frequentAddresses (inserted : [String]) -> [(UIImage, String, String, UIImage?, UIColor)] {
+    static func frequentAddresses (_ inserted: [String]) -> [(UIImage, String, String, UIImage?, UIColor)] {
         return freqAlgorithm(inserted)
     }
     
-    static func findContact(econtact: EnzevalosContact)-> [CNContact]{
+    static func findContact(_ econtact: EnzevalosContact)-> [CNContact]{
         var result = [CNContact]()
         if let identifier = econtact.cnidentifier {
             // 1. Look up identifier string
@@ -183,12 +183,12 @@ class AddressHandler {
     }
     
     
-    static func proveMatching(result: CNContact, addresses: [MailAddress])-> Bool{
+    static func proveMatching(_ result: CNContact, addresses: [MailAddress])-> Bool{
         var match: Bool = false
         for email in result.emailAddresses{
             for adr in addresses{
-                let adrRest = email.value as! String
-                if adrRest.lowercaseString == adr.mailAddress.lowercaseString {
+                let adrRest = email.value as String
+                if adrRest.lowercased() == adr.mailAddress.lowercased() {
                     match = true
                     break
                 }
@@ -201,7 +201,7 @@ class AddressHandler {
     }
     
     
-    static func contactByEmail(mailaddreses: [MailAddress]) -> [CNContact] {
+    static func contactByEmail(_ mailaddreses: [MailAddress]) -> [CNContact] {
         var contacts: [CNContact] = []
         let predicate = NSPredicate { (evaluatedObject, bindings) -> Bool in
             guard let evaluatedContact = evaluatedObject as? CNContact else {
@@ -217,7 +217,7 @@ class AddressHandler {
             return exists
         }
         do{
-            try contacts = AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName), CNContactEmailAddressesKey, CNContactImageDataKey, CNContactThumbnailImageDataKey])
+            try contacts = AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: CNContactFormatterStyle.fullName), CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor])
         }
         catch {}
         return contacts
diff --git a/enzevalos_iphone/AnimatedSendIcon.swift b/enzevalos_iphone/AnimatedSendIcon.swift
index c1d00eefc1d199eac31ff85e344b820d7017fbd6..41958716e1304f9ac81d373cd350661222ba251a 100644
--- a/enzevalos_iphone/AnimatedSendIcon.swift
+++ b/enzevalos_iphone/AnimatedSendIcon.swift
@@ -24,9 +24,9 @@ class AnimatedSendIcon: UIView {
     
     override init(frame: CGRect) {
         super.init(frame: frame)
-        self.userInteractionEnabled = false
+        self.isUserInteractionEnabled = false
         
-        let resizing: ResizingBehavior = .AspectFit
+        let resizing: ResizingBehavior = .aspectFit
 //        let context = UIGraphicsGetCurrentContext()!
 //        //// Resize to Target Frame
 //        CGContextSaveGState(context)
@@ -36,9 +36,9 @@ class AnimatedSendIcon: UIView {
 //        
 //        self.view.transform = CGAffineTransformMakeScale(2, 2)
         
-        self.transform = CGAffineTransformMakeScale(resizedFrame.width / 200, resizedFrame.height / 110)
+        self.transform = CGAffineTransform(scaleX: resizedFrame.width / 200, y: resizedFrame.height / 110)
         //        self = UIView(frame: frame) //UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 110))
-        self.backgroundColor = UIColor.whiteColor()
+        self.backgroundColor = UIColor.white
         
         size = CGSize(width: width, height: height)
         sizeSmall = CGSize(width: width*f, height: height*f)
@@ -61,7 +61,7 @@ class AnimatedSendIcon: UIView {
     }
     
     func switchIcons() {
-        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
+        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.001 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
             print("zPosition") // TODO: In swift 3, the layer switch seems to work, remove this then
             self.square.layer.zPosition = self.isOnTop ? 1 : 0
             self.square2.layer.zPosition = !self.isOnTop ? 1 : 0
@@ -69,38 +69,38 @@ class AnimatedSendIcon: UIView {
         })
         
         if !isOnTop {
-            UIView.animateKeyframesWithDuration(0.75, delay: 0, options: .CalculationModeCubicPaced, animations: {
-                UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.25, animations: {
+            UIView.animateKeyframes(withDuration: 0.75, delay: 0, options: .calculationModeCubicPaced, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
                     self.square.frame = CGRect(x: 10, y: 20, width: self.width*0.95, height: self.height*0.95)
                     self.square2.frame = CGRect(x: 120, y: 20, width: self.width*0.85, height: self.height*0.85)
                 })
-                UIView.addKeyframeWithRelativeStartTime(0.25, relativeDuration: 0.5, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.5, animations: {
                     self.square.frame = CGRect(x: 70, y: 5, width: self.width*0.78, height: self.height*0.78)
                     self.square.alpha = 0.6
                     self.square2.alpha = 1.0
                     self.square2.frame = CGRect(x: 60, y: 40, width: self.width*0.95, height: self.height*0.95)
                 })
                 
-                UIView.addKeyframeWithRelativeStartTime(0.75, relativeDuration: 0.25, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
                     self.square.frame = CGRect(origin: self.back, size: self.sizeSmall)
                     self.square2.frame = CGRect(origin: self.front, size: self.size)
                 })
                 
                 }, completion: nil)
         } else {
-            UIView.animateKeyframesWithDuration(0.75, delay: 0, options: .CalculationModeCubicPaced, animations: {
-                UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.25, animations: {
+            UIView.animateKeyframes(withDuration: 0.75, delay: 0, options: .calculationModeCubicPaced, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
                     self.square2.frame = CGRect(x: 10, y: 20, width: self.width*0.95, height: self.height*0.95)
                     self.square.frame = CGRect(x: 120, y: 20, width: self.width*0.85, height: self.height*0.85)
                 })
-                UIView.addKeyframeWithRelativeStartTime(0.25, relativeDuration: 0.5, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.5, animations: {
                     self.square2.frame = CGRect(x: 70, y: 5, width: self.width*0.85, height: self.height*0.85)
                     self.square2.alpha = 0.6
                     self.square.alpha = 1.0
                     self.square.frame = CGRect(x: 60, y: 40, width: self.width*0.95, height: self.height*0.95)
                 })
                 
-                UIView.addKeyframeWithRelativeStartTime(0.75, relativeDuration: 0.25, animations: {
+                UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
                     self.square2.frame = CGRect(origin: self.back, size: self.sizeSmall)
                     self.square.frame = CGRect(origin: self.front, size: self.size)
                 })
@@ -110,12 +110,12 @@ class AnimatedSendIcon: UIView {
     }
     
     @objc internal enum ResizingBehavior: Int {
-        case AspectFit /// The content is proportionally resized to fit into the target rectangle.
-        case AspectFill /// The content is proportionally resized to completely fill the target rectangle.
-        case Stretch /// The content is stretched to match the entire target rectangle.
-        case Center /// The content is centered in the target rectangle, but it is NOT resized.
+        case aspectFit /// The content is proportionally resized to fit into the target rectangle.
+        case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
+        case stretch /// The content is stretched to match the entire target rectangle.
+        case center /// The content is centered in the target rectangle, but it is NOT resized.
         
-        internal func apply(rect rect: CGRect, target: CGRect) -> CGRect {
+        internal func apply(rect: CGRect, target: CGRect) -> CGRect {
             if rect == target || target == CGRect.zero {
                 return rect
             }
@@ -125,15 +125,15 @@ class AnimatedSendIcon: UIView {
             scales.height = abs(target.height / rect.height)
             
             switch self {
-            case .AspectFit:
+            case .aspectFit:
                 scales.width = min(scales.width, scales.height)
                 scales.height = scales.width
-            case .AspectFill:
+            case .aspectFill:
                 scales.width = max(scales.width, scales.height)
                 scales.height = scales.width
-            case .Stretch:
+            case .stretch:
                 break
-            case .Center:
+            case .center:
                 scales.width = 1
                 scales.height = 1
             }
diff --git a/enzevalos_iphone/AppDelegate.swift b/enzevalos_iphone/AppDelegate.swift
index a3858ace4900917c6c1812806f77568a7efa9bcf..32bce471f225afc3a8436e23d377d9b83033508a 100644
--- a/enzevalos_iphone/AppDelegate.swift
+++ b/enzevalos_iphone/AppDelegate.swift
@@ -20,14 +20,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
     var mailHandler = MailHandler()
     private var initialViewController : UIViewController? = nil
     
-    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
+    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
         // Override point for customization after application launch.
         //UINavigationBar.appearance().backgroundColor = UIColor.blueColor()
         ThemeManager.currentTheme()
         
-        if (!NSUserDefaults.standardUserDefaults().boolForKey("launchedBefore")) {
+        if (!UserDefaults.standard.bool(forKey: "launchedBefore")) {
             self.initialViewController = self.window?.rootViewController
-            self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
+            self.window = UIWindow(frame: UIScreen.main.bounds)
             //self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("onboarding")
             self.window?.rootViewController = Onboarding.onboarding(self.credentialCheck)
             self.window?.makeKeyAndVisible()
@@ -53,59 +53,67 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         //self.onboardingDone()
     }
     
-    func contactCheck(accessGranted: Bool) {
+    func contactCheck(_ accessGranted: Bool) {
         if accessGranted {
-            self.onboardingDone()
+            self.setupKeys()
         }
         else {
             //self.onboardingDone()
-            dispatch_async(dispatch_get_main_queue(),{
-                self.showMessage(NSLocalizedString("AccessNotGranted", comment: ""), completion: self.onboardingDone)
+            DispatchQueue.main.async(execute: {
+                self.showMessage(NSLocalizedString("AccessNotGranted", comment: ""), completion: self.setupKeys)
             });
         }
     }
     
-    func onboardingDone() {
+    func setupKeys() {
         self.window?.rootViewController = Onboarding.keyHandlingView()
-        Onboarding.keyHandling()
-        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "launchedBefore")
+        DispatchQueue.main.async(execute: {
+            Onboarding.keyHandling()
+            self.onboardingDone()
+        });
+    }
+    
+    func onboardingDone() {
+        /*self.window?.rootViewController = Onboarding.keyHandlingView()
+        Onboarding.keyHandling()*/
+        UserDefaults.standard.set(true, forKey: "launchedBefore")
         self.window?.rootViewController = self.initialViewController!
     }
     
-    func applicationWillResignActive(application: UIApplication) {
+    func applicationWillResignActive(_ application: UIApplication) {
         // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
         // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     }
     
-    func applicationDidEnterBackground(application: UIApplication) {
+    func applicationDidEnterBackground(_ application: UIApplication) {
         // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
         //DataHandler.handler.terminate()
     }
     
-    func applicationWillEnterForeground(application: UIApplication) {
+    func applicationWillEnterForeground(_ application: UIApplication) {
         // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     }
     
-    func applicationDidBecomeActive(application: UIApplication) {
+    func applicationDidBecomeActive(_ application: UIApplication) {
         // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     }
     
-    func applicationWillTerminate(application: UIApplication) {
+    func applicationWillTerminate(_ application: UIApplication) {
         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
         DataHandler.handler.terminate()
     }
     
     
     class func getAppDelegate() -> AppDelegate {
-        return UIApplication.sharedApplication().delegate as! AppDelegate
+        return UIApplication.shared.delegate as! AppDelegate
     }
     
     
-    func showMessage(message: String, completion: (() -> Void)? ) {
-        let alertController = UIAlertController(title: "Enzevalos", message: message, preferredStyle: UIAlertControllerStyle.Alert)
+    func showMessage(_ message: String, completion: (() -> Void)? ) {
+        let alertController = UIAlertController(title: "Enzevalos", message: message, preferredStyle: UIAlertControllerStyle.alert)
         
-        let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (action : UIAlertAction) -> Void in
+        let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action : UIAlertAction) -> Void in
             if let cb = completion {
                 cb()
             }
@@ -116,35 +124,35 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         //let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
         let presentedViewController = self.window!.rootViewController!//pushedViewControllers[pushedViewControllers.count - 1]
         
-        presentedViewController.presentViewController(alertController, animated: false, completion: nil)
+        presentedViewController.present(alertController, animated: false, completion: nil)
     }
     
     
-    func requestForAccess(completionHandler: (accessGranted: Bool) -> Void) {
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
+    func requestForAccess(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
         
         switch authorizationStatus {
-        case .Authorized:
-            completionHandler(accessGranted: true)
+        case .authorized:
+            completionHandler(true)
             
-        case .NotDetermined:
-            self.contactStore.requestAccessForEntityType(CNEntityType.Contacts, completionHandler: { (access, accessError) -> Void in
+        case .notDetermined:
+            self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
                 if access {
-                    completionHandler(accessGranted: access)
+                    completionHandler(access)
                 }
                 else {
-                    if authorizationStatus == CNAuthorizationStatus.Denied {
+                    if authorizationStatus == CNAuthorizationStatus.denied {
                         /*dispatch_async(dispatch_get_main_queue(), { () -> Void in
                             let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                             self.showMessage(message, completion: nil)
                         })*/
                     }
-                    completionHandler(accessGranted: false)
+                    completionHandler(false)
                 }
             })
             
         default:
-            completionHandler(accessGranted: false)
+            completionHandler(false)
         }
     }
     
diff --git a/enzevalos_iphone/CNMailAddressesExtension.swift b/enzevalos_iphone/CNMailAddressesExtension.swift
index 865cfff797466a9ebca6e3c6e9714a25a70c2f02..25ab0881bb06e2ddcdf7e56445264a6f516d5a27 100644
--- a/enzevalos_iphone/CNMailAddressesExtension.swift
+++ b/enzevalos_iphone/CNMailAddressesExtension.swift
@@ -9,29 +9,29 @@
 import Foundation
 import Contacts
 
-public class CNMailAddressExtension: MailAddress{
+open class CNMailAddressExtension: MailAddress{
 
-    public var mailAddress:String{
+    open var mailAddress:String{
         get{
             return label.value as! String
         }
     }
-    public var label: CNLabeledValue
+    open var label: CNLabeledValue<<#ValueType: NSCopying & NSSecureCoding#>>
     
-    public var prefEnc: Bool{
+    open var prefEnc: Bool{
         get{
             return false
         }
         set{
         }
     }
-    public var hasKey: Bool{
+    open var hasKey: Bool{
         get{
             return false
         }
     }
     
-    init(addr: CNLabeledValue){
+    init(addr: CNLabeledValue<<#ValueType: NSCopying & NSSecureCoding#>>){
         self.label = addr
     }
     
diff --git a/enzevalos_iphone/CollectionDataDelegate.swift b/enzevalos_iphone/CollectionDataDelegate.swift
index 3faf2aa4b0e2a153b93263d045920979cef849be..92d408e7d0d9d2854bf3266061a2f41d59017e10 100644
--- a/enzevalos_iphone/CollectionDataDelegate.swift
+++ b/enzevalos_iphone/CollectionDataDelegate.swift
@@ -10,28 +10,28 @@ import UIKit
 
 class CollectionDataDelegate : NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
     
-    var suggestionFunc : ([String] -> [(UIImage, String, String, UIImage?, UIColor)])
+    var suggestionFunc : (([String]) -> [(UIImage, String, String, UIImage?, UIColor)])
                     //[bereits eingetragene emailadresse] -> [(Kontaktbild, Name, Emailadresse, emailTypeImage)]
     var alreadyInserted : [String] = []
     var insertCallback : (String, String) -> Void = {(name : String, address : String) -> Void in return}
     
     static let maxFrequent = 10
     
-    init(suggestionFunc: [String] -> [(UIImage, String, String, UIImage?, UIColor)], insertCallback : (String, String) -> Void){
+    init(suggestionFunc: @escaping ([String]) -> [(UIImage, String, String, UIImage?, UIColor)], insertCallback : @escaping (String, String) -> Void){
         self.suggestionFunc = suggestionFunc
         self.insertCallback = insertCallback
         super.init()
     }
     
-    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
+    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         print(suggestionFunc(alreadyInserted).count)
         print("section: ",section)
         return suggestionFunc(alreadyInserted).count
     }
     
-    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
+    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         print(indexPath.row, indexPath.description)
-        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("frequent", forIndexPath: indexPath) as! FrequentCell
+        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "frequent", for: indexPath) as! FrequentCell
         cell.img.layer.cornerRadius = cell.img.frame.height/2
         cell.img.clipsToBounds = true
         cell.img.image = suggestionFunc(alreadyInserted)[indexPath.row].0
@@ -48,7 +48,7 @@ class CollectionDataDelegate : NSObject, UICollectionViewDataSource, UICollectio
         return cell
     }
     
-    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
+    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         let tuple = suggestionFunc(alreadyInserted)[indexPath.row]
         insertCallback(tuple.1, tuple.2)
     }
diff --git a/enzevalos_iphone/Contact.swift b/enzevalos_iphone/Contact.swift
index f2ed6237e415d11bd84c8e8bb2fe7b11be7e3a82..9743b47a460130411921cf969d1c05670fb39e1e 100644
--- a/enzevalos_iphone/Contact.swift
+++ b/enzevalos_iphone/Contact.swift
@@ -17,7 +17,7 @@ public protocol Contact {
     func getMailAddresses()-> [MailAddress]
 }
 extension Contact{
-    private func makeImageFromName(name: String)->UIImage{
+    private func makeImageFromName(_ name: String)->UIImage{
         var text : NSAttributedString
         var tag:  String
         tag = String()
@@ -25,7 +25,7 @@ extension Contact{
             tag = String(name.characters.first!)
         }
         
-        text = NSAttributedString(string: tag.capitalizedString, attributes: [NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont.systemFontOfSize(32.2)])
+        text = NSAttributedString(string: tag.capitalized, attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 32.2)])
         
         var myBounds = CGRect()
         myBounds.size.width = 70
@@ -37,15 +37,15 @@ extension Contact{
         //
         // Clip context to a circle
         //
-        let path = CGPathCreateWithEllipseInRect(myBounds, nil);
-        CGContextAddPath(context!, path);
-        CGContextClip(context!);
+        let path = CGPath(ellipseIn: myBounds, transform: nil);
+        context!.addPath(path);
+        context!.clip();
         
         //
         // Fill background of context
         //
-        CGContextSetFillColorWithColor(context!, self.getColor().CGColor)
-        CGContextFillRect(context!, CGRectMake(0, 0, myBounds.size.width, myBounds.size.height));
+        context!.setFillColor(self.getColor().cgColor)
+        context!.fill(CGRect(x: 0, y: 0, width: myBounds.size.width, height: myBounds.size.height));
         
         
         //
@@ -53,7 +53,7 @@ extension Contact{
         //
         let textSize = text.size()
         
-        text.drawInRect(CGRectMake(myBounds.size.width/2 - textSize.width/2, myBounds.size.height/2 - textSize.height/2,textSize.width, textSize.height))
+        text.draw(in: CGRect(x: myBounds.size.width/2 - textSize.width/2, y: myBounds.size.height/2 - textSize.height/2,width: textSize.width, height: textSize.height))
         
         
         let snapshot = UIGraphicsGetImageFromCurrentImageContext();
diff --git a/enzevalos_iphone/ContactViewController.swift b/enzevalos_iphone/ContactViewController.swift
index 1ed9946a06c088086509d7c61d62fa2cd9dc6884..2d0d9d872844cb012569fd6f15bdd6a6610cf422 100644
--- a/enzevalos_iphone/ContactViewController.swift
+++ b/enzevalos_iphone/ContactViewController.swift
@@ -10,6 +10,30 @@ import Foundation
 import UIKit
 import Contacts
 import ContactsUI
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l < r
+  case (nil, _?):
+    return true
+  default:
+    return false
+  }
+}
+
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l > r
+  default:
+    return rhs < lhs
+  }
+}
+
 
 class ContactViewController: UIViewController {
     var keyRecord: KeyRecord? = nil
@@ -42,34 +66,34 @@ class ContactViewController: UIViewController {
         }
     }
 
-    override func viewWillAppear(animated: Bool) {
+    override func viewWillAppear(_ animated: Bool) {
         if let row = tableView.indexPathForSelectedRow {
-            tableView.deselectRowAtIndexPath(row, animated: false)
+            tableView.deselectRow(at: row, animated: false)
         }
     }
 
     func prepareContactSheet() {
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                uiContact = try AppDelegate.getAppDelegate().contactStore.unifiedContactWithIdentifier(keyRecord!.cnContact!.identifier, keysToFetch: [CNContactViewController.descriptorForRequiredKeys()])
+                uiContact = try AppDelegate.getAppDelegate().contactStore.unifiedContact(withIdentifier: keyRecord!.cnContact!.identifier, keysToFetch: [CNContactViewController.descriptorForRequiredKeys()])
             } catch {
                 //contact doesn't exist or we don't have authorization
                 //TODO: handle missing authorization
             }
         }
         if let conUI = uiContact {
-            let infoButton = UIButton(type: .InfoLight)
-            vc = CNContactViewController(forContact: conUI)
+            let infoButton = UIButton(type: .infoLight)
+            vc = CNContactViewController(for: conUI)
             vc!.contactStore = AppDelegate.getAppDelegate().contactStore // nötig?
-            infoButton.addTarget(self, action: #selector(ContactViewController.showContact), forControlEvents: .TouchUpInside)
+            infoButton.addTarget(self, action: #selector(ContactViewController.showContact), for: .touchUpInside)
             self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: infoButton)
         } else {
-            let addButton = UIButton(type: .ContactAdd)
+            let addButton = UIButton(type: .contactAdd)
             vc = CNContactViewController(forNewContact: keyRecord!.cnContact)
             vc!.contactStore = AppDelegate.getAppDelegate().contactStore // nötig?
             vc!.delegate = self
-            addButton.addTarget(self, action: #selector(ContactViewController.showContact), forControlEvents: .TouchUpInside)
+            addButton.addTarget(self, action: #selector(ContactViewController.showContact), for: .touchUpInside)
             self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: addButton)
         }
     }
@@ -86,29 +110,29 @@ class ContactViewController: UIViewController {
         let context = UIGraphicsGetCurrentContext()
 
         // Clip context to a circle
-        let path = CGPathCreateWithEllipseInRect(myBounds, nil);
-        CGContextAddPath(context!, path);
-        CGContextClip(context!);
+        let path = CGPath(ellipseIn: myBounds, transform: nil);
+        context!.addPath(path);
+        context!.clip();
 
         // Fill background of context
-        var bgColor: CGColor = ThemeManager.defaultColor.CGColor
+        var bgColor: CGColor = ThemeManager.defaultColor.cgColor
         if keyRecord!.isVerified {
-            bgColor = Theme.Very_strong_security_indicator.encryptedVerifiedMessageColor.CGColor
+            bgColor = Theme.very_strong_security_indicator.encryptedVerifiedMessageColor.cgColor
         } else if !keyRecord!.hasKey {
-            bgColor = Theme.Very_strong_security_indicator.uncryptedMessageColor.CGColor
+            bgColor = Theme.very_strong_security_indicator.uncryptedMessageColor.cgColor
         }
-        CGContextSetFillColorWithColor(context!, bgColor)
-        CGContextFillRect(context!, CGRectMake(0, 0, myBounds.size.width, myBounds.size.height));
+        context!.setFillColor(bgColor)
+        context!.fill(CGRect(x: 0, y: 0, width: myBounds.size.width, height: myBounds.size.height));
 
         let iconSize = CGFloat(50)
-        let frame = CGRectMake(myBounds.size.width / 2 - iconSize / 2, myBounds.size.height / 2 - iconSize / 2, iconSize, iconSize)
+        let frame = CGRect(x: myBounds.size.width / 2 - iconSize / 2, y: myBounds.size.height / 2 - iconSize / 2, width: iconSize, height: iconSize)
 
         if keyRecord!.hasKey {
             IconsStyleKit.drawLetter(frame: frame, fillBackground: true)
         } else if keyRecord!.isVerified {
-            IconsStyleKit.drawLetter(frame: frame, color: UIColor.whiteColor())
+            IconsStyleKit.drawLetter(frame: frame, color: UIColor.white)
         } else {
-            IconsStyleKit.drawPostcard(frame: frame, resizing: .AspectFit, color: UIColor.whiteColor())
+            IconsStyleKit.drawPostcard(frame: frame, resizing: .aspectFit, color: UIColor.white)
         }
 
         let img = UIGraphicsGetImageFromCurrentImageContext();
@@ -120,22 +144,22 @@ class ContactViewController: UIViewController {
         self.navigationController?.pushViewController(vc!, animated: true)
     }
 
-    func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {
-        self.navigationController?.popViewControllerAnimated(true)
+    func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
+        self.navigationController?.popViewController(animated: true)
         prepareContactSheet()
     }
 
-    @IBAction func actionButton(sender: AnyObject) {
+    @IBAction func actionButton(_ sender: AnyObject) {
         if (sender as? UIButton)?.titleLabel?.text == NSLocalizedString("toEncrypted", comment: "switch to encrypted") {
-            let myPath = NSIndexPath(forRow: 1, inSection: 0)
-            tableView.selectRowAtIndexPath(myPath, animated: false, scrollPosition: .None)
-            performSegueWithIdentifier("otherRecord", sender: nil)
+            let myPath = IndexPath(row: 1, section: 0)
+            tableView.selectRow(at: myPath, animated: false, scrollPosition: .none)
+            performSegue(withIdentifier: "otherRecord", sender: nil)
         }
     }
 
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "newMail" {
-            let navigationController = segue.destinationViewController as? UINavigationController
+            let navigationController = segue.destination as? UINavigationController
             let controller = navigationController?.topViewController as? SendViewController
             let indexPath = tableView.indexPathForSelectedRow
             if controller != nil {
@@ -145,13 +169,13 @@ class ContactViewController: UIViewController {
                 }
             }
         } else if segue.identifier == "mailList" {
-            let DestinationViewController: ListViewController = segue.destinationViewController as! ListViewController
+            let DestinationViewController: ListViewController = segue.destination as! ListViewController
             DestinationViewController.contact = keyRecord
         } else if segue.identifier == "otherRecord" {
-            let DestinationViewController: ContactViewController = segue.destinationViewController as! ContactViewController
+            let DestinationViewController: ContactViewController = segue.destination as! ContactViewController
             let indexPath = tableView.indexPathForSelectedRow
             if let r = otherRecords {
-                if let indexPath = indexPath where indexPath.section == 3 && !(keyRecord?.hasKey ?? false) || indexPath.section == 4 && (keyRecord?.hasKey ?? false) {
+                if let indexPath = indexPath, indexPath.section == 3 && !(keyRecord?.hasKey ?? false) || indexPath.section == 4 && (keyRecord?.hasKey ?? false) {
                     let destinationRecord = r[indexPath.row]
                     DestinationViewController.keyRecord = destinationRecord
                 } else {
@@ -159,7 +183,7 @@ class ContactViewController: UIViewController {
                 }
             }
         } else if segue.identifier == "keyView" {
-            let destinationViewController: KeyViewController = segue.destinationViewController as! KeyViewController
+            let destinationViewController: KeyViewController = segue.destination as! KeyViewController
             destinationViewController.record = keyRecord
         }
     }
@@ -170,12 +194,12 @@ extension ContactViewController: CNContactViewControllerDelegate {
 }
 
 extension ContactViewController: UITableViewDataSource {
-    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
+    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         if keyRecord != nil {
             switch indexPath.section {
             case 0:
                 if indexPath.row == 0 {
-                    let cell = tableView.dequeueReusableCellWithIdentifier("ContactViewCell") as! ContactViewCell
+                    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactViewCell") as! ContactViewCell
                     cell.contactImage.image = keyRecord!.cnContact!.getImageOrDefault()
                     cell.contactImage.layer.cornerRadius = cell.contactImage.frame.height / 2
                     cell.contactImage.clipsToBounds = true
@@ -191,48 +215,48 @@ extension ContactViewController: UITableViewDataSource {
                     }
                     return cell
                 } else if indexPath.row == 1 {
-                    let actionCell = tableView.dequeueReusableCellWithIdentifier("ActionCell", forIndexPath: indexPath) as! ActionCell
+                    let actionCell = tableView.dequeueReusableCell(withIdentifier: "ActionCell", for: indexPath) as! ActionCell
                     if keyRecord!.hasKey {
-                        actionCell.Button.setTitle(NSLocalizedString("verifyNow", comment: "Verify now"), forState: .Normal)
+                        actionCell.Button.setTitle(NSLocalizedString("verifyNow", comment: "Verify now"), for: UIControlState())
                     } else if otherRecords?.filter({ $0.hasKey }).count > 0 {
-                        actionCell.Button.setTitle(NSLocalizedString("toEncrypted", comment: "switch to encrypted"), forState: .Normal)
+                        actionCell.Button.setTitle(NSLocalizedString("toEncrypted", comment: "switch to encrypted"), for: UIControlState())
                     } else {
-                        actionCell.Button.setTitle(NSLocalizedString("invite", comment: "Invide contact to use encryption"), forState: .Normal)
+                        actionCell.Button.setTitle(NSLocalizedString("invite", comment: "Invide contact to use encryption"), for: UIControlState())
                     }
                     return actionCell
                 }
             case 1:
-                let cell = tableView.dequeueReusableCellWithIdentifier("MailCell") as! MailCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "MailCell") as! MailCell
                 if let address = keyRecord?.ezContact.getMailAddresses()[indexPath.item].mailAddress {
-                    if let highlightEmail = highlightEmail where highlightEmail.containsString(address) {
+                    if let highlightEmail = highlightEmail, highlightEmail.contains(address) {
                         cell.detailLabel.textColor = view.tintColor
                         cell.titleLabel.textColor = view.tintColor
                     }
                     cell.detailLabel.text = address
                 }
                 if let label = keyRecord?.ezContact.getMailAddresses()[indexPath.item].label.label {
-                    cell.titleLabel.text = CNLabeledValue.localizedStringForLabel(label)
+                    cell.titleLabel.text = CNLabeledValue.localizedString(forLabel: label)
                 } else {
                     cell.titleLabel.text = ""
                 }
 
                 return cell
             case 2:
-                let cell = tableView.dequeueReusableCellWithIdentifier("AllMails", forIndexPath: indexPath)
+                let cell = tableView.dequeueReusableCell(withIdentifier: "AllMails", for: indexPath)
                 cell.textLabel?.text = NSLocalizedString("allMessages", comment: "show all messages")
                 return cell
             case 3 where (keyRecord?.hasKey) ?? false:
-                let cell = tableView.dequeueReusableCellWithIdentifier("KeyCell", forIndexPath: indexPath)
+                let cell = tableView.dequeueReusableCell(withIdentifier: "KeyCell", for: indexPath)
                 cell.textLabel?.text = NSLocalizedString("Details", comment: "Details")
                 return cell
             case 3 where !((keyRecord?.hasKey) ?? false):
-                let cell = tableView.dequeueReusableCellWithIdentifier("RecordCell", forIndexPath: indexPath) as! RecordCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "RecordCell", for: indexPath) as! RecordCell
                 if let r = otherRecords {
                     if let key = r[indexPath.row].key, let time = EnzevalosEncryptionHandler.getEncryption(.PGP)?.getKey(key)?.discoveryTime {
-                        let dateFormatter = NSDateFormatter()
-                        dateFormatter.locale = NSLocale.currentLocale()
-                        dateFormatter.dateStyle = .MediumStyle
-                        cell.dateLabel.text = dateFormatter.stringFromDate(time)
+                        let dateFormatter = DateFormatter()
+                        dateFormatter.locale = Locale.current
+                        dateFormatter.dateStyle = .medium
+                        cell.dateLabel.text = dateFormatter.string(from: time)
                         cell.iconImage.image = IconsStyleKit.imageOfLetter
                     } else {
                         cell.dateLabel.text = ""
@@ -242,17 +266,17 @@ extension ContactViewController: UITableViewDataSource {
                 }
                 return cell
             case 4 where !((keyRecord?.hasKey) ?? false):
-                let cell = tableView.dequeueReusableCellWithIdentifier("KeyCell", forIndexPath: indexPath)
+                let cell = tableView.dequeueReusableCell(withIdentifier: "KeyCell", for: indexPath)
                 cell.textLabel?.text = "abc"
                 return cell
             case 4 where (keyRecord?.hasKey) ?? false:
-                let cell = tableView.dequeueReusableCellWithIdentifier("RecordCell", forIndexPath: indexPath) as! RecordCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "RecordCell", for: indexPath) as! RecordCell
                 if let r = otherRecords {
                     if let key = r[indexPath.row].key, let time = EnzevalosEncryptionHandler.getEncryption(.PGP)?.getKey(key)?.discoveryTime {
-                        let dateFormatter = NSDateFormatter()
-                        dateFormatter.locale = NSLocale.currentLocale()
-                        dateFormatter.dateStyle = .MediumStyle
-                        cell.dateLabel.text = dateFormatter.stringFromDate(time)
+                        let dateFormatter = DateFormatter()
+                        dateFormatter.locale = Locale.current
+                        dateFormatter.dateStyle = .medium
+                        cell.dateLabel.text = dateFormatter.string(from: time)
                         cell.iconImage.image = IconsStyleKit.imageOfLetter
                     } else {
                         cell.dateLabel.text = ""
@@ -265,21 +289,21 @@ extension ContactViewController: UITableViewDataSource {
                 break
             }
         }
-        return tableView.dequeueReusableCellWithIdentifier("MailCell", forIndexPath: indexPath)
+        return tableView.dequeueReusableCell(withIdentifier: "MailCell", for: indexPath)
     }
 
-    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+    func numberOfSections(in tableView: UITableView) -> Int {
         var sections = 3
         if keyRecord?.ezContact.records.count > 1 {
             sections += 1
         }
-        if let hasKey = keyRecord?.hasKey where hasKey {
+        if let hasKey = keyRecord?.hasKey, hasKey {
             sections += 1
         }
         return sections
     }
 
-    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         if let con = keyRecord {
             switch section {
             case 0:
@@ -305,7 +329,7 @@ extension ContactViewController: UITableViewDataSource {
         return 1
     }
 
-    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
+    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         switch section {
         case 1:
             return NSLocalizedString("connectedAddresses", comment: "All addresses connected to this keyrecord")
@@ -318,7 +342,7 @@ extension ContactViewController: UITableViewDataSource {
         }
     }
 
-    func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
+    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
         if section == 0 {
             return "Mit diesem Kontakt kommunizieren Sie zu 93% verschlüsselt und im Durchschnitt 2,3 x pro Woche." // Nur ein Test
         }
@@ -327,41 +351,41 @@ extension ContactViewController: UITableViewDataSource {
 }
 
 extension ContactViewController: UITableViewDelegate {
-    func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
+    func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
         if indexPath.section == 1 {
             return true
         }
         return false
     }
 
-    func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
+    func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
         return action == #selector(copy(_:))
     }
 
-    func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
+    func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
         if indexPath.section == 1 {
-            UIPasteboard.generalPasteboard().string = keyRecord!.ezContact.getMailAddresses()[indexPath.row].mailAddress
+            UIPasteboard.general.string = keyRecord!.ezContact.getMailAddresses()[indexPath.row].mailAddress
         }
     }
 }
 
 extension ContactViewController: UINavigationControllerDelegate {
-    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
+    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
         switch operation {
-        case .Push where (tableView.indexPathForSelectedRow?.section == 4 && ((keyRecord?.hasKey) ?? false) || tableView.indexPathForSelectedRow?.section == 3 && !((keyRecord?.hasKey) ?? false)) || tableView.indexPathForSelectedRow?.section == 0:
+        case .push where (tableView.indexPathForSelectedRow?.section == 4 && ((keyRecord?.hasKey) ?? false) || tableView.indexPathForSelectedRow?.section == 3 && !((keyRecord?.hasKey) ?? false)) || tableView.indexPathForSelectedRow?.section == 0:
             return FlipTransition()
         default:
             return nil
         }
     }
 
-    func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
+    func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
         return nil
     }
 }
 
 extension ContactViewController: UIGestureRecognizerDelegate {
-    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
+    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }
 }
diff --git a/enzevalos_iphone/DataHandler.swift b/enzevalos_iphone/DataHandler.swift
index a12e15522f7759cabea9bea2d9d3da947d0d1009..93ebf8e7fc37b433114033bea79e02d32c54caec 100644
--- a/enzevalos_iphone/DataHandler.swift
+++ b/enzevalos_iphone/DataHandler.swift
@@ -9,6 +9,30 @@
 import UIKit
 import CoreData
 import Contacts
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l < r
+  case (nil, _?):
+    return true
+  default:
+    return false
+  }
+}
+
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l > r
+  default:
+    return rhs < lhs
+  }
+}
+
 
 //TODO: TO Felder mit Strings
 // KeyRecord mergen?? IMAP Snyc?
@@ -47,10 +71,10 @@ class DataHandler {
     
     func cleanCache() {
         for m in mails {
-            managedObjectContext.deleteObject(m)
+            managedObjectContext.delete(m)
         }
         for c in contacts {
-            managedObjectContext.deleteObject(c)
+            managedObjectContext.delete(c)
         }
         mails.removeAll()
         contacts.removeAll()
@@ -60,25 +84,25 @@ class DataHandler {
     
     init() {
         // This resource is the same name as your xcdatamodeld contained in your project.
-        guard let modelURL = NSBundle.mainBundle().URLForResource("enzevalos_iphone", withExtension:"momd") else {
+        guard let modelURL = Bundle.main.url(forResource: "enzevalos_iphone", withExtension:"momd") else {
             fatalError("Error loading model from bundle")
         }
         // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
-        guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
+        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
             fatalError("Error initializing mom from: \(modelURL)")
         }
         let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
-        self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
+        self.managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
         self.managedObjectContext.persistentStoreCoordinator = psc
         
-        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
+        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
         let docURL = urls[urls.endIndex-1]
         /* The directory the application uses to store the Core Data store file.
          This code uses a file named "DataModel.sqlite" in the application's documents directory.
          */
-        let storeURL = docURL.URLByAppendingPathComponent("enzevalos_iphone.sqlite")
+        let storeURL = docURL.appendingPathComponent("enzevalos_iphone.sqlite")
         do {
-            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
+            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
         } catch {
             fatalError("Error migrating store: \(error)")
         }
@@ -109,13 +133,13 @@ class DataHandler {
                 let c = contacts.last! as EnzevalosContact
                 if  !c.hasKey{
                     for m in c.from{
-                            managedObjectContext.deleteObject(m as NSManagedObject)
-                            if let index = mails.indexOf(m) {
-                                mails.removeAtIndex(index)
+                            managedObjectContext.delete(m as NSManagedObject)
+                            if let index = mails.index(of: m) {
+                                mails.remove(at: index)
                             }
                         }
                     contacts.removeLast()
-                    managedObjectContext.deleteObject(c)
+                    managedObjectContext.delete(c)
                 }
             }
             receiverRecords = getRecords()
@@ -127,10 +151,10 @@ class DataHandler {
             while c.from.count > MaxMailsPerRecord {
                 let last = c.from.last!
                 print("delete \(last.uid) of \(last.from.address)")
-                managedObjectContext.deleteObject(last)
+                managedObjectContext.delete(last)
                 save()
-                if let index = mails.indexOf(last) {
-                        mails.removeAtIndex(index)
+                if let index = mails.index(of: last) {
+                        mails.remove(at: index)
                 }
             }
         }
@@ -139,12 +163,12 @@ class DataHandler {
     
     // Save, load, search
     
-    private func find(entityName: String, type:String, search: String) -> [AnyObject]?{
+    private func find(_ entityName: String, type:String, search: String) -> [AnyObject]?{
         let fReq: NSFetchRequest = NSFetchRequest(entityName: entityName)
         fReq.predicate = NSPredicate(format:"\(type) CONTAINS '\(search)' ")
         let result: [AnyObject]?
         do {
-            result = try self.managedObjectContext.executeFetchRequest(fReq)
+            result = try self.managedObjectContext.fetch(fReq)
         } catch _ as NSError {
             result = nil
             return nil
@@ -152,12 +176,12 @@ class DataHandler {
         return result
     }
     
-    private func findNum (entityName: String, type:String, search: UInt64) -> [AnyObject]?{
+    private func findNum (_ entityName: String, type:String, search: UInt64) -> [AnyObject]?{
         let fReq: NSFetchRequest = NSFetchRequest(entityName: entityName)
         fReq.predicate = NSPredicate(format:"\(type) = %D ",search)
         let result: [AnyObject]?
         do {
-            result = try self.managedObjectContext.executeFetchRequest(fReq)
+            result = try self.managedObjectContext.fetch(fReq)
         } catch _ as NSError{
             result = nil
             return nil
@@ -166,11 +190,11 @@ class DataHandler {
     }
 
     
-    private func findAll(entityName:String)->[AnyObject]? {
+    private func findAll(_ entityName:String)->[AnyObject]? {
         let fReq: NSFetchRequest = NSFetchRequest(entityName: entityName)
         let result: [AnyObject]?
         do {
-            result = try self.managedObjectContext.executeFetchRequest(fReq)
+            result = try self.managedObjectContext.fetch(fReq)
         } catch _ as NSError {
             result = nil
             return nil
@@ -181,14 +205,14 @@ class DataHandler {
     
     
     // -------- Handle mail addresses ---------
-    func getMailAddress(address: String, temporary: Bool)-> MailAddress {
+    func getMailAddress(_ address: String, temporary: Bool)-> MailAddress {
         let search  = find("Mail_Address", type: "address", search: address)
         if search == nil || search!.count == 0 {
             if temporary{
                 return CNMailAddressExtension(addr: address)
             }
             else{
-                let mail_address =  NSEntityDescription.insertNewObjectForEntityForName("Mail_Address",inManagedObjectContext: managedObjectContext) as! Mail_Address
+                let mail_address =  NSEntityDescription.insertNewObject(forEntityName: "Mail_Address",into: managedObjectContext) as! Mail_Address
                 mail_address.address = address
                 mail_address.prefer_encryption = false
                 return mail_address
@@ -199,7 +223,7 @@ class DataHandler {
         }
     }
     
-    func getMailAddressesByString(addresses: [String], temporary: Bool) -> [MailAddress]{
+    func getMailAddressesByString(_ addresses: [String], temporary: Bool) -> [MailAddress]{
         var mailaddresses = [MailAddress]()
         for adr in addresses{
             mailaddresses.append(getMailAddress(adr, temporary: temporary))
@@ -207,11 +231,11 @@ class DataHandler {
         return mailaddresses    
     }
     
-    func getMailAddressByMCOAddress(address: MCOAddress, temporary: Bool) -> MailAddress {
+    func getMailAddressByMCOAddress(_ address: MCOAddress, temporary: Bool) -> MailAddress {
         return getMailAddress(address.mailbox!, temporary: temporary)
     }
     
-    func getMailAddressesByMCOAddresses(addresses: [MCOAddress])->[Mail_Address] {
+    func getMailAddressesByMCOAddresses(_ addresses: [MCOAddress])->[Mail_Address] {
         var mailaddresses = [Mail_Address]()
         for adr in addresses{
             mailaddresses.append(getMailAddressByMCOAddress(adr, temporary: false) as! Mail_Address)
@@ -225,7 +249,7 @@ class DataHandler {
     // By mail-address via String or MCOAddress
     // If no enzevalos contact exists. One is created.
     
-    func getContactByAddress(address: String) -> EnzevalosContact {
+    func getContactByAddress(_ address: String) -> EnzevalosContact {
         // Core function
         for c in contacts {
             if c.addresses != nil {
@@ -238,7 +262,7 @@ class DataHandler {
             }
             if let cnContact = c.cnContact {
                 for adr in cnContact.emailAddresses {
-                    let name = adr.value as! String
+                    let name = adr.value as String
                     if name == address {
                         let adr = getMailAddress(address, temporary: false) as! Mail_Address
                         c.addToAddresses(adr)
@@ -252,7 +276,7 @@ class DataHandler {
         let search = find("EnzevalosContact", type: "addresses", search: address)
         var contact: EnzevalosContact
         if search == nil || search!.count == 0 {
-            contact = NSEntityDescription.insertNewObjectForEntityForName("EnzevalosContact", inManagedObjectContext: managedObjectContext) as! EnzevalosContact
+            contact = NSEntityDescription.insertNewObject(forEntityName: "EnzevalosContact", into: managedObjectContext) as! EnzevalosContact
             contact.displayname = address
             let adr = getMailAddress(address, temporary: false)as! Mail_Address
             contact.addToAddresses(adr)
@@ -267,7 +291,7 @@ class DataHandler {
     }
     
     
-    func getContact(name: String, address: String, key: String, prefer_enc: Bool) -> EnzevalosContact {
+    func getContact(_ name: String, address: String, key: String, prefer_enc: Bool) -> EnzevalosContact {
         let contact = getContactByAddress(address)
         contact.displayname = name
         contact.getAddress(address)?.keyID = key
@@ -277,7 +301,7 @@ class DataHandler {
  
 
     
-    func getContacts(receivers: [MCOAddress]) -> [EnzevalosContact] {
+    func getContacts(_ receivers: [MCOAddress]) -> [EnzevalosContact] {
         var contacts = [EnzevalosContact]()
         var contact: EnzevalosContact
         for r in receivers{
@@ -287,7 +311,7 @@ class DataHandler {
         return contacts
     }
     
-    func getContactByMCOAddress(address: MCOAddress) -> EnzevalosContact {
+    func getContactByMCOAddress(_ address: MCOAddress) -> EnzevalosContact {
         let contact =  getContactByAddress(address.mailbox!)
         if address.displayName != nil {
             contact.displayname = address.displayName
@@ -298,7 +322,7 @@ class DataHandler {
     
     
     // -------- Start handle to, cc, from addresses --------
-    private func handleFromAddress(sender: MCOAddress, fromMail: Mail, autocrypt: AutocryptContact?) {
+    private func handleFromAddress(_ sender: MCOAddress, fromMail: Mail, autocrypt: AutocryptContact?) {
         let adr: Mail_Address
         let contact = getContactByMCOAddress(sender)
         adr = contact.getAddressByMCOAddress(sender)!
@@ -309,11 +333,11 @@ class DataHandler {
         fromMail.from = adr
     }
     
-    private func handleToAddresses(receivers: [MCOAddress], mail: Mail) {
+    private func handleToAddresses(_ receivers: [MCOAddress], mail: Mail) {
         mail.addToTo(NSSet(array: getMailAddressesByMCOAddresses(receivers)))
     }
     
-    private func handleCCAddresses(cc: [MCOAddress], mail: Mail) {
+    private func handleCCAddresses(_ cc: [MCOAddress], mail: Mail) {
         mail.addToCc(NSSet(array: getMailAddressesByMCOAddresses(cc)))
     }
     
@@ -321,14 +345,14 @@ class DataHandler {
     
     // -------- End handle to, cc, from addresses --------
     
-    func createMail(uid: UInt64, sender: MCOAddress, receivers: [MCOAddress], cc: [MCOAddress], time: NSDate, received: Bool, subject: String, body: String, flags: MCOMessageFlag, record: KeyRecord?, autocrypt: AutocryptContact?) -> Mail {
+    func createMail(_ uid: UInt64, sender: MCOAddress, receivers: [MCOAddress], cc: [MCOAddress], time: Date, received: Bool, subject: String, body: String, flags: MCOMessageFlag, record: KeyRecord?, autocrypt: AutocryptContact?) -> Mail {
         
         let finding = findNum("Mail", type: "uid", search: uid)
         let mail: Mail
         
         if finding == nil || finding!.count == 0 {
             // create new mail object
-            mail  = NSEntityDescription.insertNewObjectForEntityForName("Mail", inManagedObjectContext: managedObjectContext) as! Mail
+            mail  = NSEntityDescription.insertNewObject(forEntityName: "Mail", into: managedObjectContext) as! Mail
           
             mail.body = body
             mail.date = time
@@ -421,30 +445,30 @@ class DataHandler {
             addToRecords(m,records: &records)
         }
         for r in records {
-            r.mails.sortInPlace()
+            r.mails.sort()
         }
-        records.sortInPlace()
+        records.sort()
         return records
     }
     
-    private func addToRecords(m:Mail, inout records: [KeyRecord] ){
+    private func addToRecords(_ m:Mail, records: inout [KeyRecord] ){
     
         var found = false
         for r in records {
             if r.addNewMail(m) {
                 found = true
-                records.sortInPlace()
+                records.sort()
                 break
             }
         }
         if !found {
             let r = KeyRecord(mail: m)
             records.append(r)
-            records.sortInPlace()
+            records.sort()
         }
     }
     
-    private func addToReceiverRecords(m: Mail){
+    private func addToReceiverRecords(_ m: Mail){
         addToRecords(m, records: &receiverRecords)
     }
     
@@ -455,7 +479,7 @@ class DataHandler {
             currentstate =  (result?.first as? State)!
         }
         else {
-            currentstate  = (NSEntityDescription.insertNewObjectForEntityForName("State", inManagedObjectContext: managedObjectContext) as? State)!
+            currentstate  = (NSEntityDescription.insertNewObject(forEntityName: "State", into: managedObjectContext) as? State)!
             currentstate.currentContacts = contacts.count
             currentstate.currentMails = mails.count
             currentstate.maxUID = 1
diff --git a/enzevalos_iphone/Encryption.swift b/enzevalos_iphone/Encryption.swift
index b8d2b5f6ff036b1fca28fbd178d68d190e2d1ee4..024869b2566b715235558a242deaacaa9ac30619 100644
--- a/enzevalos_iphone/Encryption.swift
+++ b/enzevalos_iphone/Encryption.swift
@@ -19,95 +19,95 @@ public protocol Encryption {
     init(encHandler: EncryptionHandler)
     
     //check whether this encryption is used in this mail. This means is it used for encryption OR signing.
-    func isUsed(mail: Mail) -> Bool
+    func isUsed(_ mail: Mail) -> Bool
     
     //check whether this encryption is used in this text. This means is it used for encryption OR signing. the key is not known to be used. nil is returned, if there is no answer to be made at the moment.
-    func isUsed(text: String, key: KeyWrapper?) -> Bool
+    func isUsed(_ text: String, key: KeyWrapper?) -> Bool
     
     //check whether this encryption is used in this mail for encryption. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForEncryption(mail: Mail) -> Bool?
+    func isUsedForEncryption(_ mail: Mail) -> Bool?
     
     //check whether this encryption is used in this text for encryption. the key is not known to be used. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForEncryption(text: String, key: KeyWrapper?) -> Bool?
+    func isUsedForEncryption(_ text: String, key: KeyWrapper?) -> Bool?
     
     //check whether this encryption is used in this mail for signing. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForSignature(mail: Mail) -> Bool?
+    func isUsedForSignature(_ mail: Mail) -> Bool?
     
     //check whether this encryption is used in this text for signing. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForSignature(text: String, key: KeyWrapper?) -> Bool?
+    func isUsedForSignature(_ text: String, key: KeyWrapper?) -> Bool?
     
     //decrypt the mails body. the decryted body will be saved in the mail object.
-    func decrypt(mail: Mail) -> String?
+    func decrypt(_ mail: Mail) -> String?
     
     //decrypt the mails body. the decryted body will be saved in the mail object.
     //Signaturechecking included. will be set in mail object too.
-    func decryptAndSignatureCheck(mail: Mail)
+    func decryptAndSignatureCheck(_ mail: Mail)
     
     //decrypt the text with the given key and return it.
-    func decrypt(text: String, keyID: String) -> String?
+    func decrypt(_ text: String, keyID: String) -> String?
     
     //check whether the mail is correctly signed with this encryption. nil is returned, if there is no answer to be made at the moment.
-    func isCorrectlySigned(mail: Mail) -> Bool?
+    func isCorrectlySigned(_ mail: Mail) -> Bool?
     
     //check whether the text is correctly signed with this encryption.
-    func isCorrectlySigned(text: String, key: KeyWrapper) -> Bool?
+    func isCorrectlySigned(_ text: String, key: KeyWrapper) -> Bool?
     
     //encrypt mail for contact
-    func encrypt(mail: Mail)
+    func encrypt(_ mail: Mail)
     
-    func encrypt(text: String, mailaddresses: [String]) -> NSData?
+    func encrypt(_ text: String, mailaddresses: [String]) -> Data?
     
     //encrypt text with key
-    func encrypt(text: String, keyIDs: [String]) -> NSData?
+    func encrypt(_ text: String, keyIDs: [String]) -> Data?
     
     //sign mail
-    func sign(mail: Mail)
+    func sign(_ mail: Mail)
     
     //sign text
-    func sign(text: String, key: KeyWrapper) -> String
+    func sign(_ text: String, key: KeyWrapper) -> String
     
     //sign and encrypt mail for contact
-    func signAndEncrypt(mail: Mail, forContact: KeyRecord)
-    func signAndEncrypt(text: String, keyIDs: [String]) -> NSData?
-    func signAndEncrypt(text: String, mailaddresses: [String]) -> NSData?
+    func signAndEncrypt(_ mail: Mail, forContact: KeyRecord)
+    func signAndEncrypt(_ text: String, keyIDs: [String]) -> Data?
+    func signAndEncrypt(_ text: String, mailaddresses: [String]) -> Data?
     
-    func addKey(keyData: NSData, forMailAddresses: [String]?) -> String?
+    func addKey(_ keyData: Data, forMailAddresses: [String]?) -> String?
     
-    func addKey(keyData: NSData, forMailAddresses: [String]?, discoveryMailUID: UInt64?) -> String?
+    func addKey(_ keyData: Data, forMailAddresses: [String]?, discoveryMailUID: UInt64?) -> String?
     
     //key is connected to the senders address, if discoveryMail is set
-    func addKey(keyData: NSData, discoveryMail: Mail?) -> String?
+    func addKey(_ keyData: Data, discoveryMail: Mail?) -> String?
     
     //will be maybe deleted... because keyWrapper will be added when constructed
     //func addKey(key: KeyWrapper, forMailAddress: [String]?, callBack: ((success: Bool) -> Void)?)
     
-    func hasKey(enzContact: EnzevalosContact) -> Bool
-    func hasKey(mailaddress: String) -> Bool
-    func getKeyIDs(enzContact: EnzevalosContact) -> [String]?
-    func getKeyIDs(mailaddress: String) -> [String]?
+    func hasKey(_ enzContact: EnzevalosContact) -> Bool
+    func hasKey(_ mailaddress: String) -> Bool
+    func getKeyIDs(_ enzContact: EnzevalosContact) -> [String]?
+    func getKeyIDs(_ mailaddress: String) -> [String]?
     
-    func getActualKeyID(mailaddress: String) -> String?
+    func getActualKeyID(_ mailaddress: String) -> String?
     
-    func keyIDExists(keyID: String) -> Bool
+    func keyIDExists(_ keyID: String) -> Bool
     
-    func getKey(keyID: String) -> KeyWrapper?
+    func getKey(_ keyID: String) -> KeyWrapper?
     
     //internaly done; update is done when a keyWrapper is manipulated
     //func updateKey(key: KeyWrapper, callBack: ((success: Bool) -> Void)?)
-    func removeKey(keyID: String) //-> Bool
+    func removeKey(_ keyID: String) //-> Bool
     
-    func removeKey(key: KeyWrapper) //-> Bool
+    func removeKey(_ key: KeyWrapper) //-> Bool
     
     //includes privatekeys too
     func removeAllKeys()
     
     func printAllKeyIDs()
     
-    func addMailAddressForKey(mailAddress: String, keyID: String)
+    func addMailAddressForKey(_ mailAddress: String, keyID: String)
     
-    func removeMailAddressForKey(mailaddress: String, keyID: String)
+    func removeMailAddressForKey(_ mailaddress: String, keyID: String)
     
-    func keyOfThisEncryption(keyData: NSData) -> Bool?
+    func keyOfThisEncryption(_ keyData: Data) -> Bool?
     
-    func autocryptHeader(adr: String) -> String
+    func autocryptHeader(_ adr: String) -> String
 }
diff --git a/enzevalos_iphone/EncryptionHandler.swift b/enzevalos_iphone/EncryptionHandler.swift
index eff94b7be711a8f39853b22a24170dc8f8eae7aa..07c6aa4f8a4a8a223b0e4bf165931f57627fc486 100644
--- a/enzevalos_iphone/EncryptionHandler.swift
+++ b/enzevalos_iphone/EncryptionHandler.swift
@@ -14,13 +14,13 @@ public protocol EncryptionHandler {
     
     
     //handle entrys in keychain for different Encryptions
-    func addPersistentData(data: NSData, searchKey: String, encryptionType: EncryptionType)
+    func addPersistentData(_ data: Data, searchKey: String, encryptionType: EncryptionType)
     //for all encryptions
     //func getPersistentData(searchKey: String) -> NSData?
-    func hasPersistentData(searchKey: String, encryptionType: EncryptionType) -> Bool
+    func hasPersistentData(_ searchKey: String, encryptionType: EncryptionType) -> Bool
     //for given encryption
-    func getPersistentData(searchKey: String, encryptionType: EncryptionType) -> NSData?
-    func replacePersistentData(searchKey: String, replacementData: NSData, encryptionType: EncryptionType) //-> Bool
-    func deletePersistentData(searchKey: String, encryptionType: EncryptionType) //-> Bool
+    func getPersistentData(_ searchKey: String, encryptionType: EncryptionType) -> Data?
+    func replacePersistentData(_ searchKey: String, replacementData: Data, encryptionType: EncryptionType) //-> Bool
+    func deletePersistentData(_ searchKey: String, encryptionType: EncryptionType) //-> Bool
     
 }
diff --git a/enzevalos_iphone/EncryptionType.swift b/enzevalos_iphone/EncryptionType.swift
index 4010dbb7262bd6ca91ede7259abd6f6787a53b92..86c6ca017c91d32186e4fe0864222eca7afccfff 100644
--- a/enzevalos_iphone/EncryptionType.swift
+++ b/enzevalos_iphone/EncryptionType.swift
@@ -19,7 +19,7 @@ public enum EncryptionType : String {
         
     }
     
-    static func typeFromAutocrypt(symbol: String)-> EncryptionType{
+    static func typeFromAutocrypt(_ symbol: String)-> EncryptionType{
         switch symbol {
         case "p":
             return .PGP
@@ -28,7 +28,7 @@ public enum EncryptionType : String {
         }
     }
     
-    static func fromString(string: String?)->EncryptionType{
+    static func fromString(_ string: String?)->EncryptionType{
         if let symbol = string{
             switch symbol {
             case "PGP":
diff --git a/enzevalos_iphone/EnzevalosContact+CoreDataProperties.swift b/enzevalos_iphone/EnzevalosContact+CoreDataProperties.swift
index 6dbbc696697a6a983318917caaa3cdd7f78005cd..cbba8b6bfbedac9581d63844b5e88500f9b4fe02 100644
--- a/enzevalos_iphone/EnzevalosContact+CoreDataProperties.swift
+++ b/enzevalos_iphone/EnzevalosContact+CoreDataProperties.swift
@@ -12,7 +12,7 @@ import CoreData
 
 extension EnzevalosContact {
 
-    @nonobjc public override class func fetchRequest() -> NSFetchRequest {
+    @nonobjc public override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
         return NSFetchRequest(entityName: "EnzevalosContact");
     }
 
@@ -27,16 +27,16 @@ extension EnzevalosContact {
 extension EnzevalosContact {
     
     @objc(addAddressesObject:)
-    @NSManaged public func addToAddresses(value: Mail_Address)
+    @NSManaged public func addToAddresses(_ value: Mail_Address)
     
     @objc(removeAddressesObject:)
-    @NSManaged public func removeFromAddresses(value: Mail_Address)
+    @NSManaged public func removeFromAddresses(_ value: Mail_Address)
     
     @objc(addAddresses:)
-    @NSManaged public func addToAddresses(values: NSSet)
+    @NSManaged public func addToAddresses(_ values: NSSet)
     
     @objc(removeAddresses:)
-    @NSManaged public func removeFromAddresses(values: NSSet)
+    @NSManaged public func removeFromAddresses(_ values: NSSet)
     
 }
 
diff --git a/enzevalos_iphone/EnzevalosEncryptionHandler.swift b/enzevalos_iphone/EnzevalosEncryptionHandler.swift
index 9b4bda8676f24493a12020c6d1cc5ea239929475..72e382506e3eaa2905e5eabd9824519860ce2759 100644
--- a/enzevalos_iphone/EnzevalosEncryptionHandler.swift
+++ b/enzevalos_iphone/EnzevalosEncryptionHandler.swift
@@ -12,12 +12,12 @@ import KeychainAccess
 //statisch von außen drauf zugreifen; auf Objekt von Encryption aus zugreifen.
 class EnzevalosEncryptionHandler : EncryptionHandler {
     private static let handler = EnzevalosEncryptionHandler()
-    private static var encryptions : [EncryptionType : Encryption] = [
-        EncryptionType.PGP : PGPEncryption(encHandler: handler)
+    private static var encryptions: [EncryptionType: Encryption] = [
+        EncryptionType.PGP: PGPEncryption(encHandler: handler)
         //TODO insert new Encryptions here
     ]
     
-    static func getEncryption(encryptionType: EncryptionType) -> Encryption? {
+    static func getEncryption(_ encryptionType: EncryptionType) -> Encryption? {
         if encryptionType == EncryptionType.PGP {
             if encryptions[EncryptionType.PGP] == nil {
                 encryptions[EncryptionType.PGP] = PGPEncryption(encHandler: handler)
@@ -28,7 +28,7 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
         return nil
     }
     
-    static func hasKey(enzContact: EnzevalosContact) -> Bool {
+    static func hasKey(_ enzContact: EnzevalosContact) -> Bool {
         for (_, enc) in encryptions {
             if enc.hasKey(enzContact) {
                 return true
@@ -37,7 +37,7 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
         return false
     }
     
-    static func hasKey(mailAddress: String) -> Bool {
+    static func hasKey(_ mailAddress: String) -> Bool {
         for (_, enc) in encryptions {
             if enc.hasKey(mailAddress) {
                 return true
@@ -48,7 +48,7 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
     
     
     
-    static func getEncryptionTypeForMail(mail: Mail) -> EncryptionType {
+    static func getEncryptionTypeForMail(_ mail: Mail) -> EncryptionType {
         for (type, enc) in encryptions {
             if enc.isUsed(mail) {
                 return type
@@ -58,7 +58,7 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
     }
     
     //a mailaddress can be found in multiple encryptionTypes
-    static func sortMailaddressesByEncryption(mailaddresses: [String]) -> [EncryptionType : [String]] {
+    static func sortMailaddressesByEncryption(_ mailaddresses: [String]) -> [EncryptionType: [String]] {
         //TODO add different Encryptions here. This may be done via an attribute Mail_Address, setting the preffered encryption
         var returnValue : [EncryptionType : [String]] = [:]
         var inserted : Bool
@@ -88,7 +88,7 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
     }
     
     //a mailaddress can be found multiple encryptionTypes
-    static func sortMailaddressesByEncryptionMCOAddress(mailaddresses: [String]) -> [EncryptionType : [MCOAddress]] {
+    static func sortMailaddressesByEncryptionMCOAddress(_ mailaddresses: [String]) -> [EncryptionType: [MCOAddress]] {
         //TODO add different Encryptions here. This may be done via an attribute Mail_Address, setting the preffered encryption
         var returnValue : [EncryptionType : [MCOAddress]] = [:]
         var inserted : Bool
@@ -126,14 +126,14 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
         keychain = Keychain(service: "Enzevalos").accessibility(.WhenUnlocked)
     }
     
-    func hasPersistentData(searchKey: String, encryptionType: EncryptionType) -> Bool {
+    func hasPersistentData(_ searchKey: String, encryptionType: EncryptionType) -> Bool {
         return getPersistentData(searchKey, encryptionType: encryptionType) != nil
     }
     
     //handle entrys in keychain for different Encryptions
-    func addPersistentData(data: NSData, searchKey: String, encryptionType: EncryptionType) {
+    func addPersistentData(_ data: Data, searchKey: String, encryptionType: EncryptionType) {
         let testData = try? keychain.getData(encryptionType.rawValue+"-"+searchKey)
-        if let tmp = testData where tmp == nil {
+        if let tmp = testData, tmp == nil {
             keychain[data: encryptionType.rawValue+"-"+searchKey] = data
         }
         
@@ -145,20 +145,20 @@ class EnzevalosEncryptionHandler : EncryptionHandler {
     }*/
     
     //for given encryption
-    func getPersistentData(searchKey: String, encryptionType: EncryptionType) -> NSData? {
+    func getPersistentData(_ searchKey: String, encryptionType: EncryptionType) -> Data? {
         return (try! keychain.getData(encryptionType.rawValue+"-"+searchKey))
     }
     
-    func replacePersistentData(searchKey: String, replacementData: NSData, encryptionType: EncryptionType) {
+    func replacePersistentData(_ searchKey: String, replacementData: Data, encryptionType: EncryptionType) {
         if !self.hasPersistentData(searchKey, encryptionType: encryptionType){//let tmp = (try? keychain.getData(encryptionType.rawValue+"-"+searchKey)), _ = tmp {
             return
         }
         keychain[data: encryptionType.rawValue+"-"+searchKey] = replacementData
     }
     
-    func deletePersistentData(searchKey: String, encryptionType: EncryptionType) {
+    func deletePersistentData(_ searchKey: String, encryptionType: EncryptionType) {
         let testData = try? keychain.getData(encryptionType.rawValue+"-"+searchKey)
-        if let tmp = testData where tmp == nil {
+        if let tmp = testData, tmp == nil {
             return
         }
         keychain[data: encryptionType.rawValue+"-"+searchKey] = nil
diff --git a/enzevalos_iphone/FlipTransition.swift b/enzevalos_iphone/FlipTransition.swift
index 8424755075e3694e6f4ac4b8a1abdab835f777b4..a5f4e2a1f8ac133ec5bb5a2dda39955b37a8e323 100644
--- a/enzevalos_iphone/FlipTransition.swift
+++ b/enzevalos_iphone/FlipTransition.swift
@@ -9,37 +9,37 @@ import Foundation
 import UIKit
 
 class FlipTransition: NSObject, UIViewControllerAnimatedTransitioning {
-    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
+    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
         return 0.3
     }
 
-    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
-        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
-        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
-        let container = transitionContext.containerView()
-        container.backgroundColor = UIColor.darkGrayColor()
+    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
+        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
+        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
+        let container = transitionContext.containerView
+        container.backgroundColor = UIColor.darkGray
         container.addSubview(toVC.view)
-        container.bringSubviewToFront(fromVC!.view)
+        container.bringSubview(toFront: fromVC!.view)
 
         var transfrom = CATransform3DIdentity
         transfrom.m34 = -0.001
         container.layer.sublayerTransform = transfrom
 
-        let initalFrame = transitionContext.initialFrameForViewController(fromVC!)
+        let initalFrame = transitionContext.initialFrame(for: fromVC!)
         toVC.view.frame = initalFrame
         fromVC!.view.frame = initalFrame
         toVC.view.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI_2), 0, 1, 0)
 
-        UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: .CurveEaseOut, animations: { () -> Void in
+        UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseOut, animations: { () -> Void in
             fromVC!.view.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_2), 0, 1, 0)
         }) { (finished: Bool) -> Void in
-            container.bringSubviewToFront(toVC.view)
-            UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0, options: .CurveEaseOut, animations: { () -> Void in
+            container.bringSubview(toFront: toVC.view)
+            UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, options: .curveEaseOut, animations: { () -> Void in
                 toVC.view.layer.transform = CATransform3DIdentity
             }) { (finished: Bool) -> Void in
 
                 fromVC!.view.layer.transform = CATransform3DIdentity
-                transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
+                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
             }
         }
     }
diff --git a/enzevalos_iphone/FrequentCell.swift b/enzevalos_iphone/FrequentCell.swift
index 7c1f477056c018db6ebf9fa8d09988042c9c3c83..b8ba0fa408648fc5df5dddd1301a6fefc35042c6 100644
--- a/enzevalos_iphone/FrequentCell.swift
+++ b/enzevalos_iphone/FrequentCell.swift
@@ -17,7 +17,7 @@ class FrequentCell : UICollectionViewCell {
     var address = ""
     var identifier = ""
     
-    func drawBackgroud(color : UIColor){
+    func drawBackgroud(_ color : UIColor){
         var myBounds = CGRect()
         myBounds.size.width = 70
         myBounds.size.height = 70
@@ -28,16 +28,16 @@ class FrequentCell : UICollectionViewCell {
         //
         // Clip context to a circle
         //
-        let path = CGPathCreateWithEllipseInRect(myBounds, nil);
-        CGContextAddPath(context!, path);
-        CGContextClip(context!);
+        let path = CGPath(ellipseIn: myBounds, transform: nil);
+        context!.addPath(path);
+        context!.clip();
         
         
         //
         // Fill background of context
         //
-        CGContextSetFillColorWithColor(context!, color.CGColor)
-        CGContextFillRect(context!, CGRectMake(0, 0, myBounds.size.width, myBounds.size.height));
+        context!.setFillColor(color.cgColor)
+        context!.fill(CGRect(x: 0, y: 0, width: myBounds.size.width, height: myBounds.size.height));
         
         let snapshot = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
diff --git a/enzevalos_iphone/IconsStyleKit.swift b/enzevalos_iphone/IconsStyleKit.swift
index 9e3b4c356ba41a30822bddac729c3659f2d7781d..b250367f4eb43ca9da234baa35f8bcca0d02afcf 100644
--- a/enzevalos_iphone/IconsStyleKit.swift
+++ b/enzevalos_iphone/IconsStyleKit.swift
@@ -15,7 +15,7 @@
 
 import UIKit
 
-public class IconsStyleKit : NSObject {
+open class IconsStyleKit : NSObject {
 
     //// Cache
 
@@ -35,26 +35,26 @@ public class IconsStyleKit : NSObject {
 
     //// Colors
 
-    public dynamic class var strokeColor: UIColor { return Cache.strokeColor }
+    open dynamic class var strokeColor: UIColor { return Cache.strokeColor }
 
     //// Drawing Methods
 
-    public dynamic class func drawLetter(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 50, height: 35), resizing: ResizingBehavior = .AspectFit, color: UIColor = IconsStyleKit.strokeColor, fillBackground: Bool = false) {
+    open dynamic class func drawLetter(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 50, height: 35), resizing: ResizingBehavior = .aspectFit, color: UIColor = IconsStyleKit.strokeColor, fillBackground: Bool = false) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 50, height: 35), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 50, resizedFrame.height / 35)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 50, y: resizedFrame.height / 35)
 
 
         //// letter Group
         //// Rectangle Drawing
         let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 1.5, y: 1.35, width: 47.4, height: 32.45), cornerRadius: 2.8)
         if fillBackground {
-            UIColor.whiteColor().setFill()
+            UIColor.white.setFill()
             rectanglePath.fill()
         }
         color.setStroke()
@@ -64,11 +64,11 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier Drawing
         let bezierPath = UIBezierPath()
-        bezierPath.moveToPoint(CGPoint(x: 2.47, y: 2.09))
-        bezierPath.addLineToPoint(CGPoint(x: 2.47, y: 2.09))
-        bezierPath.addLineToPoint(CGPoint(x: 24.38, y: 19.56))
-        bezierPath.addCurveToPoint(CGPoint(x: 26.11, y: 19.56), controlPoint1: CGPoint(x: 24.88, y: 19.97), controlPoint2: CGPoint(x: 25.6, y: 19.97))
-        bezierPath.addLineToPoint(CGPoint(x: 47.89, y: 2.09))
+        bezierPath.move(to: CGPoint(x: 2.47, y: 2.09))
+        bezierPath.addLine(to: CGPoint(x: 2.47, y: 2.09))
+        bezierPath.addLine(to: CGPoint(x: 24.38, y: 19.56))
+        bezierPath.addCurve(to: CGPoint(x: 26.11, y: 19.56), controlPoint1: CGPoint(x: 24.88, y: 19.97), controlPoint2: CGPoint(x: 25.6, y: 19.97))
+        bezierPath.addLine(to: CGPoint(x: 47.89, y: 2.09))
         color.setStroke()
         bezierPath.lineWidth = 2
         bezierPath.stroke()
@@ -76,8 +76,8 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 2 Drawing
         let bezier2Path = UIBezierPath()
-        bezier2Path.moveToPoint(CGPoint(x: 2.47, y: 33.06))
-        bezier2Path.addLineToPoint(CGPoint(x: 20.54, y: 16.5))
+        bezier2Path.move(to: CGPoint(x: 2.47, y: 33.06))
+        bezier2Path.addLine(to: CGPoint(x: 20.54, y: 16.5))
         color.setStroke()
         bezier2Path.lineWidth = 2
         bezier2Path.stroke()
@@ -85,38 +85,38 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 29.92, y: 16.5))
-        bezier3Path.addLineToPoint(CGPoint(x: 47.89, y: 33.05))
+        bezier3Path.move(to: CGPoint(x: 29.92, y: 16.5))
+        bezier3Path.addLine(to: CGPoint(x: 47.89, y: 33.05))
         color.setStroke()
         bezier3Path.lineWidth = 2
         bezier3Path.stroke()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
 
-    public dynamic class func drawLetterCorrupted(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 49, height: 34), resizing: ResizingBehavior = .AspectFit, color: UIColor = IconsStyleKit.strokeColor) {
+    open dynamic class func drawLetterCorrupted(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 49, height: 34), resizing: ResizingBehavior = .aspectFit, color: UIColor = IconsStyleKit.strokeColor) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 49, height: 34), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 49, resizedFrame.height / 34)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 49, y: resizedFrame.height / 34)
 
 
         //// letter_corrupted Group
         //// Bezier Drawing
         let bezierPath = UIBezierPath()
-        bezierPath.moveToPoint(CGPoint(x: 47.88, y: 10.44))
-        bezierPath.addLineToPoint(CGPoint(x: 47.88, y: 29.96))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.04, y: 32.79), controlPoint1: CGPoint(x: 47.88, y: 31.52), controlPoint2: CGPoint(x: 46.6, y: 32.79))
-        bezierPath.addLineToPoint(CGPoint(x: 4.32, y: 32.79))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.48, y: 29.96), controlPoint1: CGPoint(x: 2.76, y: 32.79), controlPoint2: CGPoint(x: 1.48, y: 31.52))
-        bezierPath.addLineToPoint(CGPoint(x: 1.48, y: 4.19))
-        bezierPath.addCurveToPoint(CGPoint(x: 4.32, y: 1.35), controlPoint1: CGPoint(x: 1.48, y: 2.63), controlPoint2: CGPoint(x: 2.76, y: 1.35))
-        bezierPath.addLineToPoint(CGPoint(x: 25.74, y: 1.35))
+        bezierPath.move(to: CGPoint(x: 47.88, y: 10.44))
+        bezierPath.addLine(to: CGPoint(x: 47.88, y: 29.96))
+        bezierPath.addCurve(to: CGPoint(x: 45.04, y: 32.79), controlPoint1: CGPoint(x: 47.88, y: 31.52), controlPoint2: CGPoint(x: 46.6, y: 32.79))
+        bezierPath.addLine(to: CGPoint(x: 4.32, y: 32.79))
+        bezierPath.addCurve(to: CGPoint(x: 1.48, y: 29.96), controlPoint1: CGPoint(x: 2.76, y: 32.79), controlPoint2: CGPoint(x: 1.48, y: 31.52))
+        bezierPath.addLine(to: CGPoint(x: 1.48, y: 4.19))
+        bezierPath.addCurve(to: CGPoint(x: 4.32, y: 1.35), controlPoint1: CGPoint(x: 1.48, y: 2.63), controlPoint2: CGPoint(x: 2.76, y: 1.35))
+        bezierPath.addLine(to: CGPoint(x: 25.74, y: 1.35))
         color.setStroke()
         bezierPath.lineWidth = 2
         bezierPath.stroke()
@@ -124,11 +124,11 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 2 Drawing
         let bezier2Path = UIBezierPath()
-        bezier2Path.moveToPoint(CGPoint(x: 2.45, y: 2.06))
-        bezier2Path.addLineToPoint(CGPoint(x: 2.45, y: 2.07))
-        bezier2Path.addLineToPoint(CGPoint(x: 23.89, y: 19))
-        bezier2Path.addCurveToPoint(CGPoint(x: 25.59, y: 19), controlPoint1: CGPoint(x: 24.39, y: 19.39), controlPoint2: CGPoint(x: 25.09, y: 19.39))
-        bezier2Path.addLineToPoint(CGPoint(x: 39.39, y: 8.03))
+        bezier2Path.move(to: CGPoint(x: 2.45, y: 2.06))
+        bezier2Path.addLine(to: CGPoint(x: 2.45, y: 2.07))
+        bezier2Path.addLine(to: CGPoint(x: 23.89, y: 19))
+        bezier2Path.addCurve(to: CGPoint(x: 25.59, y: 19), controlPoint1: CGPoint(x: 24.39, y: 19.39), controlPoint2: CGPoint(x: 25.09, y: 19.39))
+        bezier2Path.addLine(to: CGPoint(x: 39.39, y: 8.03))
         color.setStroke()
         bezier2Path.lineWidth = 2
         bezier2Path.stroke()
@@ -136,8 +136,8 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 2.45, y: 32.08))
-        bezier3Path.addLineToPoint(CGPoint(x: 20.13, y: 16.03))
+        bezier3Path.move(to: CGPoint(x: 2.45, y: 32.08))
+        bezier3Path.addLine(to: CGPoint(x: 20.13, y: 16.03))
         color.setStroke()
         bezier3Path.lineWidth = 2
         bezier3Path.stroke()
@@ -145,8 +145,8 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 4 Drawing
         let bezier4Path = UIBezierPath()
-        bezier4Path.moveToPoint(CGPoint(x: 29.32, y: 16.03))
-        bezier4Path.addLineToPoint(CGPoint(x: 46.91, y: 32.08))
+        bezier4Path.move(to: CGPoint(x: 29.32, y: 16.03))
+        bezier4Path.addLine(to: CGPoint(x: 46.91, y: 32.08))
         color.setStroke()
         bezier4Path.lineWidth = 2
         bezier4Path.stroke()
@@ -154,10 +154,10 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 5 Drawing
         let bezier5Path = UIBezierPath()
-        bezier5Path.moveToPoint(CGPoint(x: 25.88, y: 2.02))
-        bezier5Path.addLineToPoint(CGPoint(x: 43.37, y: 2.02))
-        bezier5Path.addCurveToPoint(CGPoint(x: 46.79, y: 4.93), controlPoint1: CGPoint(x: 45.25, y: 2.02), controlPoint2: CGPoint(x: 46.79, y: 3.33))
-        bezier5Path.addLineToPoint(CGPoint(x: 46.79, y: 11.14))
+        bezier5Path.move(to: CGPoint(x: 25.88, y: 2.02))
+        bezier5Path.addLine(to: CGPoint(x: 43.37, y: 2.02))
+        bezier5Path.addCurve(to: CGPoint(x: 46.79, y: 4.93), controlPoint1: CGPoint(x: 45.25, y: 2.02), controlPoint2: CGPoint(x: 46.79, y: 3.33))
+        bezier5Path.addLine(to: CGPoint(x: 46.79, y: 11.14))
         color.setStroke()
         bezier5Path.lineWidth = 1.5
         bezier5Path.stroke()
@@ -165,60 +165,60 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier 6 Drawing
         let bezier6Path = UIBezierPath()
-        bezier6Path.moveToPoint(CGPoint(x: 40.19, y: 8.73))
-        bezier6Path.addLineToPoint(CGPoint(x: 43.79, y: 8.73))
+        bezier6Path.move(to: CGPoint(x: 40.19, y: 8.73))
+        bezier6Path.addLine(to: CGPoint(x: 43.79, y: 8.73))
         color.setStroke()
         bezier6Path.lineWidth = 1.5
-        bezier6Path.lineCapStyle = .Round
+        bezier6Path.lineCapStyle = .round
         bezier6Path.stroke()
 
 
         //// Bezier 7 Drawing
         let bezier7Path = UIBezierPath()
-        bezier7Path.moveToPoint(CGPoint(x: 26.69, y: 5.44))
-        bezier7Path.addLineToPoint(CGPoint(x: 43.79, y: 5.44))
+        bezier7Path.move(to: CGPoint(x: 26.69, y: 5.44))
+        bezier7Path.addLine(to: CGPoint(x: 43.79, y: 5.44))
         color.setStroke()
         bezier7Path.lineWidth = 1.5
-        bezier7Path.lineCapStyle = .Round
+        bezier7Path.lineCapStyle = .round
         bezier7Path.stroke()
 
 
         //// Bezier 8 Drawing
         let bezier8Path = UIBezierPath()
-        bezier8Path.moveToPoint(CGPoint(x: 25.17, y: 0.36))
-        bezier8Path.addCurveToPoint(CGPoint(x: 25.88, y: 4.71), controlPoint1: CGPoint(x: 25.18, y: 0.72), controlPoint2: CGPoint(x: 25.02, y: 3.45))
-        bezier8Path.addCurveToPoint(CGPoint(x: 28.72, y: 7.43), controlPoint1: CGPoint(x: 26.79, y: 6.04), controlPoint2: CGPoint(x: 27.19, y: 7.56))
-        bezier8Path.addCurveToPoint(CGPoint(x: 32.58, y: 6.78), controlPoint1: CGPoint(x: 30.35, y: 7.28), controlPoint2: CGPoint(x: 32.04, y: 6.48))
-        bezier8Path.addCurveToPoint(CGPoint(x: 34.29, y: 8.22), controlPoint1: CGPoint(x: 33.23, y: 7.16), controlPoint2: CGPoint(x: 33.57, y: 7.5))
-        bezier8Path.addCurveToPoint(CGPoint(x: 39.63, y: 8.16), controlPoint1: CGPoint(x: 35.4, y: 9.32), controlPoint2: CGPoint(x: 38.11, y: 6.91))
-        bezier8Path.addCurveToPoint(CGPoint(x: 41.78, y: 10.3), controlPoint1: CGPoint(x: 40.55, y: 8.92), controlPoint2: CGPoint(x: 40.64, y: 9.53))
-        bezier8Path.addCurveToPoint(CGPoint(x: 44.84, y: 10.71), controlPoint1: CGPoint(x: 42.53, y: 10.81), controlPoint2: CGPoint(x: 43.69, y: 10.16))
-        bezier8Path.addCurveToPoint(CGPoint(x: 46.82, y: 11.1), controlPoint1: CGPoint(x: 45.38, y: 10.97), controlPoint2: CGPoint(x: 45.98, y: 11.12))
-        bezier8Path.addCurveToPoint(CGPoint(x: 48.04, y: 11.16), controlPoint1: CGPoint(x: 47.3, y: 11.09), controlPoint2: CGPoint(x: 47.7, y: 11.16))
+        bezier8Path.move(to: CGPoint(x: 25.17, y: 0.36))
+        bezier8Path.addCurve(to: CGPoint(x: 25.88, y: 4.71), controlPoint1: CGPoint(x: 25.18, y: 0.72), controlPoint2: CGPoint(x: 25.02, y: 3.45))
+        bezier8Path.addCurve(to: CGPoint(x: 28.72, y: 7.43), controlPoint1: CGPoint(x: 26.79, y: 6.04), controlPoint2: CGPoint(x: 27.19, y: 7.56))
+        bezier8Path.addCurve(to: CGPoint(x: 32.58, y: 6.78), controlPoint1: CGPoint(x: 30.35, y: 7.28), controlPoint2: CGPoint(x: 32.04, y: 6.48))
+        bezier8Path.addCurve(to: CGPoint(x: 34.29, y: 8.22), controlPoint1: CGPoint(x: 33.23, y: 7.16), controlPoint2: CGPoint(x: 33.57, y: 7.5))
+        bezier8Path.addCurve(to: CGPoint(x: 39.63, y: 8.16), controlPoint1: CGPoint(x: 35.4, y: 9.32), controlPoint2: CGPoint(x: 38.11, y: 6.91))
+        bezier8Path.addCurve(to: CGPoint(x: 41.78, y: 10.3), controlPoint1: CGPoint(x: 40.55, y: 8.92), controlPoint2: CGPoint(x: 40.64, y: 9.53))
+        bezier8Path.addCurve(to: CGPoint(x: 44.84, y: 10.71), controlPoint1: CGPoint(x: 42.53, y: 10.81), controlPoint2: CGPoint(x: 43.69, y: 10.16))
+        bezier8Path.addCurve(to: CGPoint(x: 46.82, y: 11.1), controlPoint1: CGPoint(x: 45.38, y: 10.97), controlPoint2: CGPoint(x: 45.98, y: 11.12))
+        bezier8Path.addCurve(to: CGPoint(x: 48.04, y: 11.16), controlPoint1: CGPoint(x: 47.3, y: 11.09), controlPoint2: CGPoint(x: 47.7, y: 11.16))
         color.setStroke()
         bezier8Path.lineWidth = 1.5
         bezier8Path.stroke()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
 
-    public dynamic class func drawPostcard(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 49, height: 34), resizing: ResizingBehavior = .AspectFit, color: UIColor = IconsStyleKit.strokeColor, fillBackground: Bool = false) {
+    open dynamic class func drawPostcard(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 49, height: 34), resizing: ResizingBehavior = .aspectFit, color: UIColor = IconsStyleKit.strokeColor, fillBackground: Bool = false) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 49, height: 34), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 49, resizedFrame.height / 34)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 49, y: resizedFrame.height / 34)
 
 
         //// letter_open Group
         //// Rectangle Drawing
         let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 1.5, y: 1.35, width: 46.4, height: 31.45), cornerRadius: 2.8)
         if fillBackground {
-            UIColor.whiteColor().setFill()
+            UIColor.white.setFill()
             rectanglePath.fill()
         }
         color.setStroke()
@@ -228,179 +228,179 @@ public class IconsStyleKit : NSObject {
 
         //// Bezier Drawing
         let bezierPath = UIBezierPath()
-        bezierPath.moveToPoint(CGPoint(x: 5.15, y: 27.39))
-        bezierPath.addLineToPoint(CGPoint(x: 20.32, y: 27.39))
+        bezierPath.move(to: CGPoint(x: 5.15, y: 27.39))
+        bezierPath.addLine(to: CGPoint(x: 20.32, y: 27.39))
         color.setStroke()
         bezierPath.lineWidth = 2
-        bezierPath.lineCapStyle = .Round
+        bezierPath.lineCapStyle = .round
         bezierPath.stroke()
 
 
         //// Bezier 2 Drawing
         let bezier2Path = UIBezierPath()
-        bezier2Path.moveToPoint(CGPoint(x: 5.15, y: 22.57))
-        bezier2Path.addLineToPoint(CGPoint(x: 20.32, y: 22.57))
+        bezier2Path.move(to: CGPoint(x: 5.15, y: 22.57))
+        bezier2Path.addLine(to: CGPoint(x: 20.32, y: 22.57))
         color.setStroke()
         bezier2Path.lineWidth = 2
-        bezier2Path.lineCapStyle = .Round
+        bezier2Path.lineCapStyle = .round
         bezier2Path.stroke()
 
 
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 5.15, y: 17.75))
-        bezier3Path.addLineToPoint(CGPoint(x: 20.32, y: 17.75))
+        bezier3Path.move(to: CGPoint(x: 5.15, y: 17.75))
+        bezier3Path.addLine(to: CGPoint(x: 20.32, y: 17.75))
         color.setStroke()
         bezier3Path.lineWidth = 2
-        bezier3Path.lineCapStyle = .Round
+        bezier3Path.lineCapStyle = .round
         bezier3Path.stroke()
 
 
         //// Bezier 4 Drawing
         let bezier4Path = UIBezierPath()
-        bezier4Path.moveToPoint(CGPoint(x: 5.15, y: 12.93))
-        bezier4Path.addLineToPoint(CGPoint(x: 20.32, y: 12.93))
+        bezier4Path.move(to: CGPoint(x: 5.15, y: 12.93))
+        bezier4Path.addLine(to: CGPoint(x: 20.32, y: 12.93))
         color.setStroke()
         bezier4Path.lineWidth = 2
-        bezier4Path.lineCapStyle = .Round
+        bezier4Path.lineCapStyle = .round
         bezier4Path.stroke()
 
 
         //// Bezier 5 Drawing
         let bezier5Path = UIBezierPath()
-        bezier5Path.moveToPoint(CGPoint(x: 5.15, y: 8.11))
-        bezier5Path.addLineToPoint(CGPoint(x: 20.32, y: 8.11))
+        bezier5Path.move(to: CGPoint(x: 5.15, y: 8.11))
+        bezier5Path.addLine(to: CGPoint(x: 20.32, y: 8.11))
         color.setStroke()
         bezier5Path.lineWidth = 2
-        bezier5Path.lineCapStyle = .Round
+        bezier5Path.lineCapStyle = .round
         bezier5Path.stroke()
 
 
         //// Bezier 6 Drawing
         let bezier6Path = UIBezierPath()
-        bezier6Path.moveToPoint(CGPoint(x: 24.52, y: 28.55))
-        bezier6Path.addLineToPoint(CGPoint(x: 24.52, y: 6.34))
+        bezier6Path.move(to: CGPoint(x: 24.52, y: 28.55))
+        bezier6Path.addLine(to: CGPoint(x: 24.52, y: 6.34))
         color.setStroke()
         bezier6Path.lineWidth = 2
-        bezier6Path.lineCapStyle = .Round
+        bezier6Path.lineCapStyle = .round
         bezier6Path.stroke()
 
 
         //// Bezier 7 Drawing
         let bezier7Path = UIBezierPath()
-        bezier7Path.moveToPoint(CGPoint(x: 28.79, y: 27.08))
-        bezier7Path.addLineToPoint(CGPoint(x: 43.97, y: 27.08))
+        bezier7Path.move(to: CGPoint(x: 28.79, y: 27.08))
+        bezier7Path.addLine(to: CGPoint(x: 43.97, y: 27.08))
         color.setStroke()
         bezier7Path.lineWidth = 2
-        bezier7Path.lineCapStyle = .Round
+        bezier7Path.lineCapStyle = .round
         bezier7Path.stroke()
 
 
         //// Bezier 8 Drawing
         let bezier8Path = UIBezierPath()
-        bezier8Path.moveToPoint(CGPoint(x: 28.79, y: 22.26))
-        bezier8Path.addLineToPoint(CGPoint(x: 43.97, y: 22.26))
+        bezier8Path.move(to: CGPoint(x: 28.79, y: 22.26))
+        bezier8Path.addLine(to: CGPoint(x: 43.97, y: 22.26))
         color.setStroke()
         bezier8Path.lineWidth = 2
-        bezier8Path.lineCapStyle = .Round
+        bezier8Path.lineCapStyle = .round
         bezier8Path.stroke()
 
 
         //// Bezier 9 Drawing
         let bezier9Path = UIBezierPath()
-        bezier9Path.moveToPoint(CGPoint(x: 28.79, y: 17.45))
-        bezier9Path.addLineToPoint(CGPoint(x: 43.97, y: 17.45))
+        bezier9Path.move(to: CGPoint(x: 28.79, y: 17.45))
+        bezier9Path.addLine(to: CGPoint(x: 43.97, y: 17.45))
         color.setStroke()
         bezier9Path.lineWidth = 2
-        bezier9Path.lineCapStyle = .Round
+        bezier9Path.lineCapStyle = .round
         bezier9Path.stroke()
 
 
         //// Bezier 10 Drawing
         let bezier10Path = UIBezierPath()
-        bezier10Path.moveToPoint(CGPoint(x: 38.03, y: 12.73))
-        bezier10Path.addLineToPoint(CGPoint(x: 42.27, y: 12.73))
-        bezier10Path.addCurveToPoint(CGPoint(x: 43.97, y: 11.03), controlPoint1: CGPoint(x: 43.21, y: 12.73), controlPoint2: CGPoint(x: 43.97, y: 11.96))
-        bezier10Path.addLineToPoint(CGPoint(x: 43.97, y: 6.79))
-        bezier10Path.addCurveToPoint(CGPoint(x: 42.27, y: 5.08), controlPoint1: CGPoint(x: 43.97, y: 5.85), controlPoint2: CGPoint(x: 43.21, y: 5.08))
-        bezier10Path.addLineToPoint(CGPoint(x: 38.03, y: 5.08))
-        bezier10Path.addCurveToPoint(CGPoint(x: 36.33, y: 6.79), controlPoint1: CGPoint(x: 37.09, y: 5.08), controlPoint2: CGPoint(x: 36.33, y: 5.85))
-        bezier10Path.addLineToPoint(CGPoint(x: 36.33, y: 11.03))
-        bezier10Path.addCurveToPoint(CGPoint(x: 38.03, y: 12.73), controlPoint1: CGPoint(x: 36.33, y: 11.96), controlPoint2: CGPoint(x: 37.09, y: 12.73))
-        bezier10Path.closePath()
+        bezier10Path.move(to: CGPoint(x: 38.03, y: 12.73))
+        bezier10Path.addLine(to: CGPoint(x: 42.27, y: 12.73))
+        bezier10Path.addCurve(to: CGPoint(x: 43.97, y: 11.03), controlPoint1: CGPoint(x: 43.21, y: 12.73), controlPoint2: CGPoint(x: 43.97, y: 11.96))
+        bezier10Path.addLine(to: CGPoint(x: 43.97, y: 6.79))
+        bezier10Path.addCurve(to: CGPoint(x: 42.27, y: 5.08), controlPoint1: CGPoint(x: 43.97, y: 5.85), controlPoint2: CGPoint(x: 43.21, y: 5.08))
+        bezier10Path.addLine(to: CGPoint(x: 38.03, y: 5.08))
+        bezier10Path.addCurve(to: CGPoint(x: 36.33, y: 6.79), controlPoint1: CGPoint(x: 37.09, y: 5.08), controlPoint2: CGPoint(x: 36.33, y: 5.85))
+        bezier10Path.addLine(to: CGPoint(x: 36.33, y: 11.03))
+        bezier10Path.addCurve(to: CGPoint(x: 38.03, y: 12.73), controlPoint1: CGPoint(x: 36.33, y: 11.96), controlPoint2: CGPoint(x: 37.09, y: 12.73))
+        bezier10Path.close()
         color.setFill()
         bezier10Path.fill()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
     
-    public dynamic class func drawLetterOpen(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 47, height: 43), resizing: ResizingBehavior = .AspectFit, color: UIColor = IconsStyleKit.strokeColor) {
+    open dynamic class func drawLetterOpen(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 47, height: 43), resizing: ResizingBehavior = .aspectFit, color: UIColor = IconsStyleKit.strokeColor) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 47, height: 43), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 47, resizedFrame.height / 43)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 47, y: resizedFrame.height / 43)
         
         //// Group
         //// Bezier Drawing
         let bezierPath = UIBezierPath()
-        bezierPath.moveToPoint(CGPoint(x: 44.79, y: 39.14))
-        bezierPath.addCurveToPoint(CGPoint(x: 44.62, y: 40), controlPoint1: CGPoint(x: 44.79, y: 39.45), controlPoint2: CGPoint(x: 44.72, y: 39.73))
-        bezierPath.addLineToPoint(CGPoint(x: 31.21, y: 26.59))
-        bezierPath.addLineToPoint(CGPoint(x: 44.58, y: 15.51))
-        bezierPath.addCurveToPoint(CGPoint(x: 44.79, y: 16.44), controlPoint1: CGPoint(x: 44.71, y: 15.79), controlPoint2: CGPoint(x: 44.79, y: 16.11))
-        bezierPath.addLineToPoint(CGPoint(x: 44.79, y: 39.14))
-        bezierPath.closePath()
-        bezierPath.moveToPoint(CGPoint(x: 42.5, y: 41.41))
-        bezierPath.addLineToPoint(CGPoint(x: 3.9, y: 41.41))
-        bezierPath.addCurveToPoint(CGPoint(x: 2.87, y: 41.16), controlPoint1: CGPoint(x: 3.53, y: 41.41), controlPoint2: CGPoint(x: 3.18, y: 41.31))
-        bezierPath.addLineToPoint(CGPoint(x: 16.42, y: 27.62))
-        bezierPath.addLineToPoint(CGPoint(x: 22.68, y: 32.81))
-        bezierPath.addCurveToPoint(CGPoint(x: 23.2, y: 32.99), controlPoint1: CGPoint(x: 22.83, y: 32.93), controlPoint2: CGPoint(x: 23.01, y: 32.99))
-        bezierPath.addCurveToPoint(CGPoint(x: 23.71, y: 32.81), controlPoint1: CGPoint(x: 23.38, y: 32.99), controlPoint2: CGPoint(x: 23.56, y: 32.93))
-        bezierPath.addLineToPoint(CGPoint(x: 29.97, y: 27.62))
-        bezierPath.addLineToPoint(CGPoint(x: 43.52, y: 41.16))
-        bezierPath.addCurveToPoint(CGPoint(x: 42.5, y: 41.41), controlPoint1: CGPoint(x: 43.21, y: 41.31), controlPoint2: CGPoint(x: 42.87, y: 41.41))
-        bezierPath.closePath()
-        bezierPath.moveToPoint(CGPoint(x: 1.6, y: 39.14))
-        bezierPath.addLineToPoint(CGPoint(x: 1.6, y: 16.44))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.82, y: 15.51), controlPoint1: CGPoint(x: 1.6, y: 16.11), controlPoint2: CGPoint(x: 1.68, y: 15.79))
-        bezierPath.addLineToPoint(CGPoint(x: 15.19, y: 26.59))
-        bezierPath.addLineToPoint(CGPoint(x: 1.78, y: 40))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.6, y: 39.14), controlPoint1: CGPoint(x: 1.67, y: 39.73), controlPoint2: CGPoint(x: 1.6, y: 39.45))
-        bezierPath.closePath()
-        bezierPath.moveToPoint(CGPoint(x: 45.38, y: 13.87))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.36, y: 13.82), controlPoint1: CGPoint(x: 45.37, y: 13.86), controlPoint2: CGPoint(x: 45.36, y: 13.84))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.32, y: 13.8), controlPoint1: CGPoint(x: 45.34, y: 13.81), controlPoint2: CGPoint(x: 45.33, y: 13.81))
-        bezierPath.addCurveToPoint(CGPoint(x: 43.34, y: 12.68), controlPoint1: CGPoint(x: 44.79, y: 13.25), controlPoint2: CGPoint(x: 44.11, y: 12.85))
-        bezierPath.addCurveToPoint(CGPoint(x: 43.23, y: 13.1), controlPoint1: CGPoint(x: 43.3, y: 12.82), controlPoint2: CGPoint(x: 43.28, y: 12.96))
-        bezierPath.addCurveToPoint(CGPoint(x: 42.99, y: 14.23), controlPoint1: CGPoint(x: 43.11, y: 13.48), controlPoint2: CGPoint(x: 43.19, y: 13.88))
-        bezierPath.addCurveToPoint(CGPoint(x: 43.44, y: 14.38), controlPoint1: CGPoint(x: 43.23, y: 14.26), controlPoint2: CGPoint(x: 43.22, y: 14.28))
-        bezierPath.addLineToPoint(CGPoint(x: 23.2, y: 31.16))
-        bezierPath.addLineToPoint(CGPoint(x: 2.96, y: 14.38))
-        bezierPath.addCurveToPoint(CGPoint(x: 3.4, y: 14.15), controlPoint1: CGPoint(x: 3.16, y: 14.29), controlPoint2: CGPoint(x: 3.17, y: 14.17))
-        bezierPath.addCurveToPoint(CGPoint(x: 2.84, y: 12.75), controlPoint1: CGPoint(x: 3.1, y: 13.74), controlPoint2: CGPoint(x: 2.86, y: 12.8))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.07, y: 13.8), controlPoint1: CGPoint(x: 2.16, y: 12.94), controlPoint2: CGPoint(x: 1.55, y: 13.3))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.04, y: 13.83), controlPoint1: CGPoint(x: 1.06, y: 13.81), controlPoint2: CGPoint(x: 1.05, y: 13.81))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.02, y: 13.87), controlPoint1: CGPoint(x: 1.03, y: 13.84), controlPoint2: CGPoint(x: 1.02, y: 13.86))
-        bezierPath.addCurveToPoint(CGPoint(x: 0, y: 16.44), controlPoint1: CGPoint(x: 0.39, y: 14.55), controlPoint2: CGPoint(x: 0, y: 15.45))
-        bezierPath.addLineToPoint(CGPoint(x: 0, y: 39.14))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.06, y: 41.77), controlPoint1: CGPoint(x: 0, y: 40.16), controlPoint2: CGPoint(x: 0.41, y: 41.08))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.09, y: 41.81), controlPoint1: CGPoint(x: 1.07, y: 41.78), controlPoint2: CGPoint(x: 1.07, y: 41.8))
-        bezierPath.addCurveToPoint(CGPoint(x: 1.1, y: 41.82), controlPoint1: CGPoint(x: 1.09, y: 41.82), controlPoint2: CGPoint(x: 1.1, y: 41.82))
-        bezierPath.addCurveToPoint(CGPoint(x: 3.9, y: 43), controlPoint1: CGPoint(x: 1.81, y: 42.55), controlPoint2: CGPoint(x: 2.8, y: 43))
-        bezierPath.addLineToPoint(CGPoint(x: 42.5, y: 43))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.29, y: 41.82), controlPoint1: CGPoint(x: 43.59, y: 43), controlPoint2: CGPoint(x: 44.58, y: 42.55))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.3, y: 41.81), controlPoint1: CGPoint(x: 45.29, y: 41.82), controlPoint2: CGPoint(x: 45.3, y: 41.82))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.34, y: 41.77), controlPoint1: CGPoint(x: 45.32, y: 41.8), controlPoint2: CGPoint(x: 45.32, y: 41.78))
-        bezierPath.addCurveToPoint(CGPoint(x: 46.4, y: 39.14), controlPoint1: CGPoint(x: 45.99, y: 41.08), controlPoint2: CGPoint(x: 46.4, y: 40.16))
-        bezierPath.addLineToPoint(CGPoint(x: 46.4, y: 16.44))
-        bezierPath.addCurveToPoint(CGPoint(x: 45.38, y: 13.87), controlPoint1: CGPoint(x: 46.4, y: 15.45), controlPoint2: CGPoint(x: 46, y: 14.55))
-        bezierPath.closePath()
+        bezierPath.move(to: CGPoint(x: 44.79, y: 39.14))
+        bezierPath.addCurve(to: CGPoint(x: 44.62, y: 40), controlPoint1: CGPoint(x: 44.79, y: 39.45), controlPoint2: CGPoint(x: 44.72, y: 39.73))
+        bezierPath.addLine(to: CGPoint(x: 31.21, y: 26.59))
+        bezierPath.addLine(to: CGPoint(x: 44.58, y: 15.51))
+        bezierPath.addCurve(to: CGPoint(x: 44.79, y: 16.44), controlPoint1: CGPoint(x: 44.71, y: 15.79), controlPoint2: CGPoint(x: 44.79, y: 16.11))
+        bezierPath.addLine(to: CGPoint(x: 44.79, y: 39.14))
+        bezierPath.close()
+        bezierPath.move(to: CGPoint(x: 42.5, y: 41.41))
+        bezierPath.addLine(to: CGPoint(x: 3.9, y: 41.41))
+        bezierPath.addCurve(to: CGPoint(x: 2.87, y: 41.16), controlPoint1: CGPoint(x: 3.53, y: 41.41), controlPoint2: CGPoint(x: 3.18, y: 41.31))
+        bezierPath.addLine(to: CGPoint(x: 16.42, y: 27.62))
+        bezierPath.addLine(to: CGPoint(x: 22.68, y: 32.81))
+        bezierPath.addCurve(to: CGPoint(x: 23.2, y: 32.99), controlPoint1: CGPoint(x: 22.83, y: 32.93), controlPoint2: CGPoint(x: 23.01, y: 32.99))
+        bezierPath.addCurve(to: CGPoint(x: 23.71, y: 32.81), controlPoint1: CGPoint(x: 23.38, y: 32.99), controlPoint2: CGPoint(x: 23.56, y: 32.93))
+        bezierPath.addLine(to: CGPoint(x: 29.97, y: 27.62))
+        bezierPath.addLine(to: CGPoint(x: 43.52, y: 41.16))
+        bezierPath.addCurve(to: CGPoint(x: 42.5, y: 41.41), controlPoint1: CGPoint(x: 43.21, y: 41.31), controlPoint2: CGPoint(x: 42.87, y: 41.41))
+        bezierPath.close()
+        bezierPath.move(to: CGPoint(x: 1.6, y: 39.14))
+        bezierPath.addLine(to: CGPoint(x: 1.6, y: 16.44))
+        bezierPath.addCurve(to: CGPoint(x: 1.82, y: 15.51), controlPoint1: CGPoint(x: 1.6, y: 16.11), controlPoint2: CGPoint(x: 1.68, y: 15.79))
+        bezierPath.addLine(to: CGPoint(x: 15.19, y: 26.59))
+        bezierPath.addLine(to: CGPoint(x: 1.78, y: 40))
+        bezierPath.addCurve(to: CGPoint(x: 1.6, y: 39.14), controlPoint1: CGPoint(x: 1.67, y: 39.73), controlPoint2: CGPoint(x: 1.6, y: 39.45))
+        bezierPath.close()
+        bezierPath.move(to: CGPoint(x: 45.38, y: 13.87))
+        bezierPath.addCurve(to: CGPoint(x: 45.36, y: 13.82), controlPoint1: CGPoint(x: 45.37, y: 13.86), controlPoint2: CGPoint(x: 45.36, y: 13.84))
+        bezierPath.addCurve(to: CGPoint(x: 45.32, y: 13.8), controlPoint1: CGPoint(x: 45.34, y: 13.81), controlPoint2: CGPoint(x: 45.33, y: 13.81))
+        bezierPath.addCurve(to: CGPoint(x: 43.34, y: 12.68), controlPoint1: CGPoint(x: 44.79, y: 13.25), controlPoint2: CGPoint(x: 44.11, y: 12.85))
+        bezierPath.addCurve(to: CGPoint(x: 43.23, y: 13.1), controlPoint1: CGPoint(x: 43.3, y: 12.82), controlPoint2: CGPoint(x: 43.28, y: 12.96))
+        bezierPath.addCurve(to: CGPoint(x: 42.99, y: 14.23), controlPoint1: CGPoint(x: 43.11, y: 13.48), controlPoint2: CGPoint(x: 43.19, y: 13.88))
+        bezierPath.addCurve(to: CGPoint(x: 43.44, y: 14.38), controlPoint1: CGPoint(x: 43.23, y: 14.26), controlPoint2: CGPoint(x: 43.22, y: 14.28))
+        bezierPath.addLine(to: CGPoint(x: 23.2, y: 31.16))
+        bezierPath.addLine(to: CGPoint(x: 2.96, y: 14.38))
+        bezierPath.addCurve(to: CGPoint(x: 3.4, y: 14.15), controlPoint1: CGPoint(x: 3.16, y: 14.29), controlPoint2: CGPoint(x: 3.17, y: 14.17))
+        bezierPath.addCurve(to: CGPoint(x: 2.84, y: 12.75), controlPoint1: CGPoint(x: 3.1, y: 13.74), controlPoint2: CGPoint(x: 2.86, y: 12.8))
+        bezierPath.addCurve(to: CGPoint(x: 1.07, y: 13.8), controlPoint1: CGPoint(x: 2.16, y: 12.94), controlPoint2: CGPoint(x: 1.55, y: 13.3))
+        bezierPath.addCurve(to: CGPoint(x: 1.04, y: 13.83), controlPoint1: CGPoint(x: 1.06, y: 13.81), controlPoint2: CGPoint(x: 1.05, y: 13.81))
+        bezierPath.addCurve(to: CGPoint(x: 1.02, y: 13.87), controlPoint1: CGPoint(x: 1.03, y: 13.84), controlPoint2: CGPoint(x: 1.02, y: 13.86))
+        bezierPath.addCurve(to: CGPoint(x: 0, y: 16.44), controlPoint1: CGPoint(x: 0.39, y: 14.55), controlPoint2: CGPoint(x: 0, y: 15.45))
+        bezierPath.addLine(to: CGPoint(x: 0, y: 39.14))
+        bezierPath.addCurve(to: CGPoint(x: 1.06, y: 41.77), controlPoint1: CGPoint(x: 0, y: 40.16), controlPoint2: CGPoint(x: 0.41, y: 41.08))
+        bezierPath.addCurve(to: CGPoint(x: 1.09, y: 41.81), controlPoint1: CGPoint(x: 1.07, y: 41.78), controlPoint2: CGPoint(x: 1.07, y: 41.8))
+        bezierPath.addCurve(to: CGPoint(x: 1.1, y: 41.82), controlPoint1: CGPoint(x: 1.09, y: 41.82), controlPoint2: CGPoint(x: 1.1, y: 41.82))
+        bezierPath.addCurve(to: CGPoint(x: 3.9, y: 43), controlPoint1: CGPoint(x: 1.81, y: 42.55), controlPoint2: CGPoint(x: 2.8, y: 43))
+        bezierPath.addLine(to: CGPoint(x: 42.5, y: 43))
+        bezierPath.addCurve(to: CGPoint(x: 45.29, y: 41.82), controlPoint1: CGPoint(x: 43.59, y: 43), controlPoint2: CGPoint(x: 44.58, y: 42.55))
+        bezierPath.addCurve(to: CGPoint(x: 45.3, y: 41.81), controlPoint1: CGPoint(x: 45.29, y: 41.82), controlPoint2: CGPoint(x: 45.3, y: 41.82))
+        bezierPath.addCurve(to: CGPoint(x: 45.34, y: 41.77), controlPoint1: CGPoint(x: 45.32, y: 41.8), controlPoint2: CGPoint(x: 45.32, y: 41.78))
+        bezierPath.addCurve(to: CGPoint(x: 46.4, y: 39.14), controlPoint1: CGPoint(x: 45.99, y: 41.08), controlPoint2: CGPoint(x: 46.4, y: 40.16))
+        bezierPath.addLine(to: CGPoint(x: 46.4, y: 16.44))
+        bezierPath.addCurve(to: CGPoint(x: 45.38, y: 13.87), controlPoint1: CGPoint(x: 46.4, y: 15.45), controlPoint2: CGPoint(x: 46, y: 14.55))
+        bezierPath.close()
         bezierPath.usesEvenOddFillRule = true
         color.setFill()
         bezierPath.fill()
@@ -408,12 +408,12 @@ public class IconsStyleKit : NSObject {
         
         //// Bezier 2 Drawing
         let bezier2Path = UIBezierPath()
-        bezier2Path.moveToPoint(CGPoint(x: 2.96, y: 15.51))
-        bezier2Path.addLineToPoint(CGPoint(x: 2.96, y: 3.99))
-        bezier2Path.addCurveToPoint(CGPoint(x: 5.79, y: 1.16), controlPoint1: CGPoint(x: 2.96, y: 2.43), controlPoint2: CGPoint(x: 4.23, y: 1.16))
-        bezier2Path.addLineToPoint(CGPoint(x: 40.6, y: 1.16))
-        bezier2Path.addCurveToPoint(CGPoint(x: 43.44, y: 3.99), controlPoint1: CGPoint(x: 42.16, y: 1.16), controlPoint2: CGPoint(x: 43.44, y: 2.43))
-        bezier2Path.addLineToPoint(CGPoint(x: 43.44, y: 15.51))
+        bezier2Path.move(to: CGPoint(x: 2.96, y: 15.51))
+        bezier2Path.addLine(to: CGPoint(x: 2.96, y: 3.99))
+        bezier2Path.addCurve(to: CGPoint(x: 5.79, y: 1.16), controlPoint1: CGPoint(x: 2.96, y: 2.43), controlPoint2: CGPoint(x: 4.23, y: 1.16))
+        bezier2Path.addLine(to: CGPoint(x: 40.6, y: 1.16))
+        bezier2Path.addCurve(to: CGPoint(x: 43.44, y: 3.99), controlPoint1: CGPoint(x: 42.16, y: 1.16), controlPoint2: CGPoint(x: 43.44, y: 2.43))
+        bezier2Path.addLine(to: CGPoint(x: 43.44, y: 15.51))
         color.setStroke()
         bezier2Path.lineWidth = 1.5
         bezier2Path.stroke()
@@ -421,10 +421,10 @@ public class IconsStyleKit : NSObject {
         
         //// Bezier 4 Drawing
         let bezier4Path = UIBezierPath()
-        bezier4Path.moveToPoint(CGPoint(x: 11.09, y: 22.41))
-        bezier4Path.addLineToPoint(CGPoint(x: 35.18, y: 22.41))
-        bezier4Path.moveToPoint(CGPoint(x: 17.82, y: 27.79))
-        bezier4Path.addLineToPoint(CGPoint(x: 28.67, y: 27.79))
+        bezier4Path.move(to: CGPoint(x: 11.09, y: 22.41))
+        bezier4Path.addLine(to: CGPoint(x: 35.18, y: 22.41))
+        bezier4Path.move(to: CGPoint(x: 17.82, y: 27.79))
+        bezier4Path.addLine(to: CGPoint(x: 28.67, y: 27.79))
         color.setStroke()
         bezier4Path.lineWidth = 1.5
         bezier4Path.stroke()
@@ -432,23 +432,23 @@ public class IconsStyleKit : NSObject {
         
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 6, y: 6.25))
-        bezier3Path.addLineToPoint(CGPoint(x: 39.86, y: 6.25))
-        bezier3Path.moveToPoint(CGPoint(x: 6, y: 11.64))
-        bezier3Path.addLineToPoint(CGPoint(x: 39.86, y: 11.64))
-        bezier3Path.moveToPoint(CGPoint(x: 6, y: 17.02))
-        bezier3Path.addLineToPoint(CGPoint(x: 39.86, y: 17.02))
+        bezier3Path.move(to: CGPoint(x: 6, y: 6.25))
+        bezier3Path.addLine(to: CGPoint(x: 39.86, y: 6.25))
+        bezier3Path.move(to: CGPoint(x: 6, y: 11.64))
+        bezier3Path.addLine(to: CGPoint(x: 39.86, y: 11.64))
+        bezier3Path.move(to: CGPoint(x: 6, y: 17.02))
+        bezier3Path.addLine(to: CGPoint(x: 39.86, y: 17.02))
         color.setStroke()
         bezier3Path.lineWidth = 1.5
-        bezier3Path.lineCapStyle = .Round
+        bezier3Path.lineCapStyle = .round
         bezier3Path.stroke()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
     }
 
     //// Generated Images
 
-    public dynamic class var imageOfLetter: UIImage {
+    open dynamic class var imageOfLetter: UIImage {
         if Cache.imageOfLetter != nil {
             return Cache.imageOfLetter!
         }
@@ -462,7 +462,7 @@ public class IconsStyleKit : NSObject {
         return Cache.imageOfLetter!
     }
 
-    public dynamic class var imageOfLetterBG: UIImage {
+    open dynamic class var imageOfLetterBG: UIImage {
         if Cache.imageOfLetterBG != nil {
             return Cache.imageOfLetterBG!
         }
@@ -476,7 +476,7 @@ public class IconsStyleKit : NSObject {
         return Cache.imageOfLetterBG!
     }
     
-    public dynamic class var imageOfLetterCorrupted: UIImage {
+    open dynamic class var imageOfLetterCorrupted: UIImage {
         if Cache.imageOfLetterCorrupted != nil {
             return Cache.imageOfLetterCorrupted!
         }
@@ -490,7 +490,7 @@ public class IconsStyleKit : NSObject {
         return Cache.imageOfLetterCorrupted!
     }
 
-    public dynamic class var imageOfPostcard: UIImage {
+    open dynamic class var imageOfPostcard: UIImage {
         if Cache.imageOfPostcard != nil {
             return Cache.imageOfPostcard!
         }
@@ -504,7 +504,7 @@ public class IconsStyleKit : NSObject {
         return Cache.imageOfPostcard!
     }
     
-    public dynamic class var imageOfPostcardBG: UIImage {
+    open dynamic class var imageOfPostcardBG: UIImage {
         if Cache.imageOfPostcardBG != nil {
             return Cache.imageOfPostcardBG!
         }
@@ -518,7 +518,7 @@ public class IconsStyleKit : NSObject {
         return Cache.imageOfPostcardBG!
     }
     
-    public dynamic class var imageOfLetterOpen: UIImage {
+    open dynamic class var imageOfLetterOpen: UIImage {
         if Cache.imageOfLetterOpen != nil {
             return Cache.imageOfLetterOpen!
         }
@@ -539,7 +539,7 @@ public class IconsStyleKit : NSObject {
         set {
             Cache.letterTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: IconsStyleKit.imageOfLetter)
+                target.perform(NSSelectorFromString("setImage:"), with: IconsStyleKit.imageOfLetter)
             }
         }
     }
@@ -549,7 +549,7 @@ public class IconsStyleKit : NSObject {
         set {
             Cache.letterCorruptedTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: IconsStyleKit.imageOfLetterCorrupted)
+                target.perform(NSSelectorFromString("setImage:"), with: IconsStyleKit.imageOfLetterCorrupted)
             }
         }
     }
@@ -559,7 +559,7 @@ public class IconsStyleKit : NSObject {
         set {
             Cache.postcardTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: IconsStyleKit.imageOfPostcard)
+                target.perform(NSSelectorFromString("setImage:"), with: IconsStyleKit.imageOfPostcard)
             }
         }
     }
@@ -569,19 +569,19 @@ public class IconsStyleKit : NSObject {
         set {
             Cache.letterOpenTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: IconsStyleKit.imageOfLetterOpen)
+                target.perform(NSSelectorFromString("setImage:"), with: IconsStyleKit.imageOfLetterOpen)
             }
         }
     }
 
 
     @objc public enum ResizingBehavior: Int {
-        case AspectFit /// The content is proportionally resized to fit into the target rectangle.
-        case AspectFill /// The content is proportionally resized to completely fill the target rectangle.
-        case Stretch /// The content is stretched to match the entire target rectangle.
-        case Center /// The content is centered in the target rectangle, but it is NOT resized.
+        case aspectFit /// The content is proportionally resized to fit into the target rectangle.
+        case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
+        case stretch /// The content is stretched to match the entire target rectangle.
+        case center /// The content is centered in the target rectangle, but it is NOT resized.
 
-        public func apply(rect rect: CGRect, target: CGRect) -> CGRect {
+        public func apply(rect: CGRect, target: CGRect) -> CGRect {
             if rect == target || target == CGRect.zero {
                 return rect
             }
@@ -591,15 +591,15 @@ public class IconsStyleKit : NSObject {
             scales.height = abs(target.height / rect.height)
 
             switch self {
-                case .AspectFit:
+                case .aspectFit:
                     scales.width = min(scales.width, scales.height)
                     scales.height = scales.width
-                case .AspectFill:
+                case .aspectFill:
                     scales.width = max(scales.width, scales.height)
                     scales.height = scales.width
-                case .Stretch:
+                case .stretch:
                     break
-                case .Center:
+                case .center:
                     scales.width = 1
                     scales.height = 1
             }
diff --git a/enzevalos_iphone/InboxCellDelegator.swift b/enzevalos_iphone/InboxCellDelegator.swift
index 52e67b6ba45f594bf1d8a71898caa316d4e5bae3..8989b99f958db5fd8ce5837c1261f0a6b1a4258a 100644
--- a/enzevalos_iphone/InboxCellDelegator.swift
+++ b/enzevalos_iphone/InboxCellDelegator.swift
@@ -7,7 +7,7 @@
 //
 
 protocol InboxCellDelegator {
-    func callSegueFromCell(mail: Mail?)
-    func callSegueFromCell2(contact: KeyRecord?)
-    func callSegueToContact(contact: KeyRecord?)
+    func callSegueFromCell(_ mail: Mail?)
+    func callSegueFromCell2(_ contact: KeyRecord?)
+    func callSegueToContact(_ contact: KeyRecord?)
 }
diff --git a/enzevalos_iphone/InboxTableViewCell.swift b/enzevalos_iphone/InboxTableViewCell.swift
index 9e8d8a5766246263ccf259898d6f76809a77e195..6f90af65018aa5b47420d01c9782fc5534ef2194 100644
--- a/enzevalos_iphone/InboxTableViewCell.swift
+++ b/enzevalos_iphone/InboxTableViewCell.swift
@@ -28,28 +28,28 @@ class InboxTableViewCell: UITableViewCell {
     @IBOutlet weak var seperator2: NSLayoutConstraint!
     @IBOutlet weak var contactButton: UIButton!
 
-    @IBAction func firstButtonPressed(sender: AnyObject) {
-        if let delegate = delegate where firstMail != nil {
+    @IBAction func firstButtonPressed(_ sender: AnyObject) {
+        if let delegate = delegate, firstMail != nil {
             firstButton.backgroundColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0)
             print("Open mail \(firstMail?.subject) | read status: \(firstMail?.isRead)")
             delegate.callSegueFromCell(firstMail)
         }
     }
 
-    @IBAction func secondButtonPressed(sender: AnyObject) {
-        if let delegate = delegate where secondMail != nil {
+    @IBAction func secondButtonPressed(_ sender: AnyObject) {
+        if let delegate = delegate, secondMail != nil {
             secondButton.backgroundColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0)
             delegate.callSegueFromCell(secondMail)
         }
     }
 
-    @IBAction func moreButtonPressed(sender: AnyObject) {
+    @IBAction func moreButtonPressed(_ sender: AnyObject) {
         if let delegate = delegate {
             delegate.callSegueFromCell2(enzContact)
         }
     }
 
-    @IBAction func contactButtonPressed(sender: AnyObject) {
+    @IBAction func contactButtonPressed(_ sender: AnyObject) {
         if let delegate = delegate {
             delegate.callSegueToContact(enzContact)
         }
@@ -59,19 +59,19 @@ class InboxTableViewCell: UITableViewCell {
         super.layoutSubviews()
 
         // prevent two buttons being pressed at the same time
-        firstButton.exclusiveTouch = true
-        secondButton.exclusiveTouch = true
-        moreButton.exclusiveTouch = true
-        contactButton.exclusiveTouch = true
-
-        firstButton.backgroundColor = UIColor.clearColor()
-        secondButton.backgroundColor = UIColor.clearColor()
-        firstButton.addTarget(self, action: .cellTouched, forControlEvents: [.TouchDown, .TouchDragEnter])
-        firstButton.addTarget(self, action: .clearCell, forControlEvents: [.TouchUpOutside, .TouchDragExit, .TouchCancel])
-        secondButton.addTarget(self, action: .cellTouched, forControlEvents: [.TouchDown, .TouchDragEnter])
-        secondButton.addTarget(self, action: .clearCell, forControlEvents: [.TouchUpOutside, .TouchDragExit, .TouchCancel])
-        seperator.constant = 1 / UIScreen.mainScreen().scale
-        seperator2.constant = 1 / UIScreen.mainScreen().scale
+        firstButton.isExclusiveTouch = true
+        secondButton.isExclusiveTouch = true
+        moreButton.isExclusiveTouch = true
+        contactButton.isExclusiveTouch = true
+
+        firstButton.backgroundColor = UIColor.clear
+        secondButton.backgroundColor = UIColor.clear
+        firstButton.addTarget(self, action: .cellTouched, for: [.touchDown, .touchDragEnter])
+        firstButton.addTarget(self, action: .clearCell, for: [.touchUpOutside, .touchDragExit, .touchCancel])
+        secondButton.addTarget(self, action: .cellTouched, for: [.touchDown, .touchDragEnter])
+        secondButton.addTarget(self, action: .clearCell, for: [.touchUpOutside, .touchDragExit, .touchCancel])
+        seperator.constant = 1 / UIScreen.main.scale
+        seperator2.constant = 1 / UIScreen.main.scale
     }
 
     var enzContact: KeyRecord? {
@@ -80,12 +80,12 @@ class InboxTableViewCell: UITableViewCell {
                 firstMail = con.mails.first
                 if con.mails.count > 1 {
                     secondMail = con.mails[1]
-                    secondButton.enabled = true
+                    secondButton.isEnabled = true
                 } else {
                     secondDateLabel.text = ""
                     secondSubjectLabel.text = ""
                     secondMessageLabel.text = NSLocalizedString("NoFurtherMessages", comment: "There is only one message from this sender.")
-                    secondButton.enabled = false
+                    secondButton.isEnabled = false
                 }
                 if con.hasKey {
                     iconView.image = IconsStyleKit.imageOfLetterBG
@@ -106,9 +106,9 @@ class InboxTableViewCell: UITableViewCell {
         didSet {
             if let mail = firstMail {
                 if !mail.isRead {
-                    firstSubjectLabel.font = UIFont.boldSystemFontOfSize(17.0)
+                    firstSubjectLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
                 } else {
-                    firstSubjectLabel.font = UIFont.systemFontOfSize(17.0)
+                    firstSubjectLabel.font = UIFont.systemFont(ofSize: 17.0)
                 }
 
                 firstSubjectLabel.text = mail.getSubjectWithFlagsString()
@@ -124,9 +124,9 @@ class InboxTableViewCell: UITableViewCell {
         didSet {
             if let mail = secondMail {
                 if !mail.isRead {
-                    secondSubjectLabel.font = UIFont.boldSystemFontOfSize(17.0)
+                    secondSubjectLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
                 } else {
-                    secondSubjectLabel.font = UIFont.systemFontOfSize(17.0)
+                    secondSubjectLabel.font = UIFont.systemFont(ofSize: 17.0)
                 }
 
                 secondSubjectLabel.text = mail.getSubjectWithFlagsString()
@@ -135,22 +135,22 @@ class InboxTableViewCell: UITableViewCell {
 
                 secondDateLabel.text = mail.timeString
 
-                moreButton.enabled = true
+                moreButton.isEnabled = true
             }
         }
     }
 
     var contact: CNContact?
 
-    func cellTouched(sender: AnyObject) {
+    func cellTouched(_ sender: AnyObject) {
         if let button = sender as? UIButton {
             button.backgroundColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0)
         }
     }
 
-    func clearCell(sender: AnyObject) {
+    func clearCell(_ sender: AnyObject) {
         if let button = sender as? UIButton {
-            UIView.animateWithDuration(0.5, animations: { button.backgroundColor = UIColor.clearColor() })
+            UIView.animate(withDuration: 0.5, animations: { button.backgroundColor = UIColor.clear })
         }
     }
 }
diff --git a/enzevalos_iphone/InboxViewController.swift b/enzevalos_iphone/InboxViewController.swift
index 42fa13ab893f28766e41dad570709fd02f95833e..50812ee312d39521f4857d06c25284eca3ecbafc 100644
--- a/enzevalos_iphone/InboxViewController.swift
+++ b/enzevalos_iphone/InboxViewController.swift
@@ -11,7 +11,7 @@ import Foundation
 import Contacts
 
 class InboxViewController: UITableViewController, InboxCellDelegator {
-    let dateFormatter = NSDateFormatter()
+    let dateFormatter = DateFormatter()
 
     /*
     var contacts: [KeyRecord] = [] {
@@ -29,7 +29,7 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
  */
 
     @IBOutlet weak var lastUpdateButton: UIBarButtonItem!
-    var lastUpdateLabel = UILabel(frame: CGRectZero)
+    var lastUpdateLabel = UILabel(frame: CGRect.zero)
     var lastUpdateText: String? {
         didSet {
             lastUpdateLabel.text = lastUpdateText
@@ -37,7 +37,7 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
         }
     }
 
-    var lastUpdate: NSDate?
+    var lastUpdate: Date?
 
 
     func addNewMail() {
@@ -70,55 +70,55 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
         tableView.sectionHeaderHeight = 1
         tableView.sectionFooterHeight = 0
 
-        self.refreshControl?.addTarget(self, action: #selector(InboxViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
+        self.refreshControl?.addTarget(self, action: #selector(InboxViewController.refresh(_:)), for: UIControlEvents.valueChanged)
         self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh")
 
         lastUpdateLabel.sizeToFit()
-        lastUpdateLabel.backgroundColor = UIColor.clearColor()
-        lastUpdateLabel.textAlignment = .Center
-        lastUpdateLabel.font = UIFont.systemFontOfSize(13)
-        lastUpdateLabel.textColor = UIColor.blackColor()
+        lastUpdateLabel.backgroundColor = UIColor.clear
+        lastUpdateLabel.textAlignment = .center
+        lastUpdateLabel.font = UIFont.systemFont(ofSize: 13)
+        lastUpdateLabel.textColor = UIColor.black
         lastUpdateButton.customView = lastUpdateLabel
 
 
         //AppDelegate.getAppDelegate().mailHandler.delegate = self
 
-        dateFormatter.locale = NSLocale.currentLocale()
-        dateFormatter.timeStyle = .MediumStyle
+        dateFormatter.locale = Locale.current
+        dateFormatter.timeStyle = .medium
 
-        tableView.registerNib(UINib(nibName: "InboxTableViewCell", bundle: nil), forCellReuseIdentifier: "inboxCell")
+        tableView.register(UINib(nibName: "InboxTableViewCell", bundle: nil), forCellReuseIdentifier: "inboxCell")
     }
 
-    func refresh(refreshControl: UIRefreshControl) {
+    func refresh(_ refreshControl: UIRefreshControl) {
         lastUpdateText = NSLocalizedString("Updating", comment: "Getting new data")
         AppDelegate.getAppDelegate().mailHandler.receiveAll(newMailCallback: addNewMail, completionCallback: getMailCompleted)
     }
 
-    func getMailCompleted(error: Bool) {
+    func getMailCompleted(_ error: Bool) {
         if let rc = self.refreshControl {
-            lastUpdate = NSDate()
+            lastUpdate = Date()
             rc.endRefreshing()
-            lastUpdateText = "\(NSLocalizedString("LastUpdate", comment: "When the last update occured")): \(dateFormatter.stringFromDate(lastUpdate!))"
+            lastUpdateText = "\(NSLocalizedString("LastUpdate", comment: "When the last update occured")): \(dateFormatter.string(from: lastUpdate!))"
             // self.contacts.sortInPlace({ $0 < $1 })
             
             self.tableView.reloadData()
         }
     }
 
-    override func viewWillAppear(animated: Bool) {
+    override func viewWillAppear(_ animated: Bool) {
         tableView.reloadData()
 
-        if lastUpdate == nil || NSDate().timeIntervalSinceDate(lastUpdate!) > 30 {
+        if lastUpdate == nil || Date().timeIntervalSince(lastUpdate!) > 30 {
             self.refreshControl?.beginRefreshingManually()
         }
     }
 
-    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return 1
     }
 
-    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
-        let cell = tableView.dequeueReusableCellWithIdentifier("inboxCell", forIndexPath: indexPath) as! InboxTableViewCell
+    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+        let cell = tableView.dequeueReusableCell(withIdentifier: "inboxCell", for: indexPath) as! InboxTableViewCell
 
         cell.delegate = self
         cell.enzContact = DataHandler.handler.receiverRecords[indexPath.section]
@@ -128,50 +128,50 @@ class InboxViewController: UITableViewController, InboxCellDelegator {
         return cell
     }
 
-    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+    override func numberOfSections(in tableView: UITableView) -> Int {
         return DataHandler.handler.receiverRecords.count
     }
 
     // set top and bottom seperator height
-    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
+    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         if section == 0 {
             return 0.01
         }
         return tableView.sectionHeaderHeight
     }
 
-    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
+    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
         return 0.01
     }
 
-    func callSegueFromCell(mail: Mail?) {
-        performSegueWithIdentifier("readMailSegue", sender: mail)
+    func callSegueFromCell(_ mail: Mail?) {
+        performSegue(withIdentifier: "readMailSegue", sender: mail)
     }
 
     //TODO: Whats that? What is the error?
 
-    func callSegueFromCell2(contact: KeyRecord?) {
-        performSegueWithIdentifier("mailListSegue", sender: contact)
+    func callSegueFromCell2(_ contact: KeyRecord?) {
+        performSegue(withIdentifier: "mailListSegue", sender: contact)
     }
 
-    func callSegueToContact(contact: KeyRecord?) {
-        performSegueWithIdentifier("contactSegue", sender: contact)
+    func callSegueToContact(_ contact: KeyRecord?) {
+        performSegue(withIdentifier: "contactSegue", sender: contact)
     }
 
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "readMailSegue" {
             if let mail = sender as? Mail {
-                let DestinationViewController: ReadViewController = segue.destinationViewController as! ReadViewController
+                let DestinationViewController: ReadViewController = segue.destination as! ReadViewController
                 DestinationViewController.mail = mail
             }
         } else if segue.identifier == "mailListSegue" {
             if let contact = sender as? KeyRecord {
-                let DestinationViewController: ListViewController = segue.destinationViewController as! ListViewController
+                let DestinationViewController: ListViewController = segue.destination as! ListViewController
                 DestinationViewController.contact = contact
             }
         } else if segue.identifier == "contactSegue" {
             if let contact = sender as? KeyRecord {
-                let DestinationViewController: ContactViewController = segue.destinationViewController as! ContactViewController
+                let DestinationViewController: ContactViewController = segue.destination as! ContactViewController
                 DestinationViewController.keyRecord = contact
             }
         }
diff --git a/enzevalos_iphone/InitViewController.swift b/enzevalos_iphone/InitViewController.swift
index 607746b900edc0ab949916e8d74b5d759bbe1be2..cc1e71857df9a06d33d4fff9ab229a705032d2ee 100644
--- a/enzevalos_iphone/InitViewController.swift
+++ b/enzevalos_iphone/InitViewController.swift
@@ -17,9 +17,9 @@ class InitViewController : UIViewController {
     }
     
     func getDefaultSettings(){
-        let manager = MCOMailProvidersManager.sharedManager()//.init() //sharedManager()
+        let manager = MCOMailProvidersManager.shared()//.init() //sharedManager()
         print(manager)
-        let path = NSBundle.mainBundle().pathForResource("providers", ofType: "json")
+        let path = Bundle.main.path(forResource: "providers", ofType: "json")
         print(path)
         //manager.registerProvidersWithFilename(path)
         print(manager.providerForEmail("alice2005@yahoo.com") == nil)
diff --git a/enzevalos_iphone/KeyRecord.swift b/enzevalos_iphone/KeyRecord.swift
index a0c788b9fc79c615431d8add3a7e63089dd9f33f..5b7dd1e72a9767f673f86b76de62923d935ae641 100644
--- a/enzevalos_iphone/KeyRecord.swift
+++ b/enzevalos_iphone/KeyRecord.swift
@@ -10,7 +10,7 @@ import Foundation
 import Contacts
 import UIKit
 
-public class KeyRecord: Record {
+open class KeyRecord: Record {
     /*
      A record contains a signing key (or none because of insecure communication), a contact (inlucding mail-addresses) and mails.
      For each key we have a different record for mailboxes. Mails and contact are affliate with the key.
@@ -19,16 +19,16 @@ public class KeyRecord: Record {
 
     let key: String?
 
-    public var addresses: [MailAddress] = [MailAddress]()
+    open var addresses: [MailAddress] = [MailAddress]()
 
-    public var name: String {
+    open var name: String {
         return ezContact.name
     }
-    public var hasKey: Bool {
+    open var hasKey: Bool {
         return key != nil
     }
 
-    public var isVerified: Bool {
+    open var isVerified: Bool {
         if let key = self.key {
             if let keywrapper = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)?.getKey(key) {
                 return keywrapper.verified
@@ -39,12 +39,12 @@ public class KeyRecord: Record {
     }
 
 
-    public var mails: [Mail] = [Mail]()
+    open var mails: [Mail] = [Mail]()
 
 
-    public var ezContact: EnzevalosContact
+    open var ezContact: EnzevalosContact
 
-    public var cnContact: CNContact? {
+    open var cnContact: CNContact? {
         return ezContact.cnContact
     }
 
@@ -54,10 +54,10 @@ public class KeyRecord: Record {
         self.mails = [Mail] ()
     }
 
-    public var image: UIImage {
+    open var image: UIImage {
         return ezContact.getImageOrDefault()
     }
-    public var color: UIColor {
+    open var color: UIColor {
         return ezContact.getColor()
     }
 
@@ -70,22 +70,22 @@ public class KeyRecord: Record {
             self.key = nil
         }
         mails.append(mail)
-        mails.sortInPlace()
+        mails.sort()
         self.ezContact = mail.from.contact
         addNewAddress(mail.from)        
     }
 
-    public static func deleteRecordFromRecordArray(records: [KeyRecord], delRecord: KeyRecord) -> [KeyRecord] {
+    open static func deleteRecordFromRecordArray(_ records: [KeyRecord], delRecord: KeyRecord) -> [KeyRecord] {
         var myrecords = [KeyRecord](records)
         let index = indexInRecords(myrecords, record: delRecord)
         if index >= 0 {
-            myrecords.removeAtIndex(index)
+            myrecords.remove(at: index)
         }
         return myrecords
     }
 
-    public static func indexInRecords(records: [KeyRecord], record: KeyRecord) -> Int {
-        for (index, r) in records.enumerate() {
+    open static func indexInRecords(_ records: [KeyRecord], record: KeyRecord) -> Int {
+        for (index, r) in records.enumerated() {
             if (matchAddresses(r, record2: record) && r.hasKey == record.hasKey && r.key == record.key) {
                 return index
             }
@@ -93,7 +93,7 @@ public class KeyRecord: Record {
         return -1
     }
 
-    private func isInRecords(records: [KeyRecord]) -> Bool {
+    private func isInRecords(_ records: [KeyRecord]) -> Bool {
         if KeyRecord.indexInRecords(records, record: self) >= 0 {
             return true
         }
@@ -101,7 +101,7 @@ public class KeyRecord: Record {
     }
 
 
-    private static func matchAddresses(record1: KeyRecord, record2: KeyRecord) -> Bool {
+    private static func matchAddresses(_ record1: KeyRecord, record2: KeyRecord) -> Bool {
         for adr1 in record1.addresses {
             for adr2 in record2.addresses {
                 if adr1.mailAddress == adr2.mailAddress {
@@ -115,14 +115,14 @@ public class KeyRecord: Record {
 
 
 
-    public func showInfos() {
+    open func showInfos() {
         print("-----------------")
         print("Name: \(ezContact.displayname) | State: \(hasKey) | #Mails: \(mails.count)")
         print("First mail: \(mails.first?.uid) | Adr: \(mails.first?.from.address) | date: \(mails.first?.date.description) ")
-        print("subj: \(mails.first?.subject?.capitalizedString)")
+        print("subj: \(mails.first?.subject?.capitalized)")
     }
 
-    public func addNewAddress(adr: MailAddress) -> Bool {
+    open func addNewAddress(_ adr: MailAddress) -> Bool {
         for a in addresses {
             if a.mailAddress == adr.mailAddress {
                 return false
@@ -132,12 +132,12 @@ public class KeyRecord: Record {
         return true
     }
 
-    public func addNewMail(mail: Mail) -> Bool {
+    open func addNewMail(_ mail: Mail) -> Bool {
         //TODO: signed only mails are dropped ??
         if mail.isSecure && self.hasKey {
             if mail.from.keyID == self.key {
                 mails.append(mail)
-                mails.sortInPlace()
+                mails.sort()
                 addNewAddress(mail.from)
                 return true
             }
@@ -160,14 +160,14 @@ public class KeyRecord: Record {
 
 
             mails.append(mail)
-            mails.sortInPlace()
+            mails.sort()
             addNewAddress(mail.from)
             return true
         }
         return false
     }
 
-    public func getImageOrDefault() -> UIImage {
+    open func getImageOrDefault() -> UIImage {
         return ezContact.getImageOrDefault()
     }
 
@@ -175,7 +175,7 @@ public class KeyRecord: Record {
 
 
 
-private func isEmpty(contact: KeyRecord) -> Bool {
+private func isEmpty(_ contact: KeyRecord) -> Bool {
     return contact.mails.count == 0
 }
 
diff --git a/enzevalos_iphone/KeyViewController.swift b/enzevalos_iphone/KeyViewController.swift
index 9ab6ebb55da4e3ed7de296c7598369deb611599a..caa5f33dff6eb240ac3c49cc86e2897bddd49ea8 100644
--- a/enzevalos_iphone/KeyViewController.swift
+++ b/enzevalos_iphone/KeyViewController.swift
@@ -17,7 +17,7 @@ class KeyViewController: UIViewController {
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        if let rec = record where rec.key != nil {
+        if let rec = record, rec.key != nil {
             //TODO use EncryptionType from KeyRecord
             keyWrapper = EnzevalosEncryptionHandler.getEncryption(.PGP)?.getKey(rec.key!)
         }
@@ -26,7 +26,7 @@ class KeyViewController: UIViewController {
 
     }
 
-    @IBAction func deleteKey(sender: AnyObject) {
+    @IBAction func deleteKey(_ sender: AnyObject) {
         if let key = keyWrapper {
             EnzevalosEncryptionHandler.getEncryption(key.type)?.removeKey(key)
         }
@@ -35,16 +35,16 @@ class KeyViewController: UIViewController {
 }
 
 extension KeyViewController: UITableViewDataSource {
-    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-        if toSectionType(section) == .KeyDetails {
+    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+        if toSectionType(section) == .keyDetails {
             var returnValue = 0
-            while(toRowType(NSIndexPath.init(forRow: returnValue, inSection: section)) != .NoKey) {
+            while(toRowType(IndexPath.init(row: returnValue, section: section)) != .noKey) {
                 returnValue += 1
             }
             return returnValue
         }
-        if toSectionType(section) == .Addresses {
-            if let key = keyWrapper where key.mailAddresses != nil {
+        if toSectionType(section) == .addresses {
+            if let key = keyWrapper, key.mailAddresses != nil {
                 return key.mailAddressesInKey!.count
             }
             return 0
@@ -52,55 +52,55 @@ extension KeyViewController: UITableViewDataSource {
         return 1
     }
 
-    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
-        if toSectionType(indexPath.section) == .KeyDetails {
-            if toRowType(indexPath) == .KeyID {
-                let cell = tableView.dequeueReusableCellWithIdentifier("KeyIDCell")!
+    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+        if toSectionType(indexPath.section) == .keyDetails {
+            if toRowType(indexPath) == .keyID {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "KeyIDCell")!
                 cell.textLabel?.text = NSLocalizedString("KeyID", comment: "Identifier of the key")
                 cell.detailTextLabel?.text = keyWrapper?.keyID
                 return cell
             }
-                else if toRowType(indexPath) == .EncryptionType {
-                let cell = tableView.dequeueReusableCellWithIdentifier("EncryptionTypeCell")!
+                else if toRowType(indexPath) == .encryptionType {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "EncryptionTypeCell")!
                 cell.detailTextLabel?.text = keyWrapper?.type.rawValue
                 cell.textLabel?.text = NSLocalizedString("EncryptionType", comment: "Type of Encryption")
                 return cell
             }
-                else if toRowType(indexPath) == .DiscoveryTime {
-                let cell = tableView.dequeueReusableCellWithIdentifier("DiscoveryTimeCell")!
+                else if toRowType(indexPath) == .discoveryTime {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoveryTimeCell")!
                 cell.textLabel?.text = NSLocalizedString("DiscoveryTime", comment: "Time of keydiscovery")
-                let formatter = NSDateFormatter()
-                formatter.locale = NSLocale.currentLocale()
-                formatter.dateStyle = .MediumStyle
-                formatter.timeStyle = .MediumStyle
+                let formatter = DateFormatter()
+                formatter.locale = Locale.current
+                formatter.dateStyle = .medium
+                formatter.timeStyle = .medium
                 if let keyWrapper = keyWrapper {
-                    cell.detailTextLabel?.text = formatter.stringFromDate(keyWrapper.discoveryTime)
+                    cell.detailTextLabel?.text = formatter.string(from: keyWrapper.discoveryTime as Date)
                 }
                 return cell
             }
-                else if toRowType(indexPath) == .DiscoveryMail {
-                let cell = tableView.dequeueReusableCellWithIdentifier("DiscoveryMailCell")!
+                else if toRowType(indexPath) == .discoveryMail {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoveryMailCell")!
                 cell.textLabel?.text = "Mail"
                 return cell
             }
-                else if toRowType(indexPath) == .Verified {
-                let cell = tableView.dequeueReusableCellWithIdentifier("VerifiedCell")!
+                else if toRowType(indexPath) == .verified {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "VerifiedCell")!
                 cell.textLabel?.text = NSLocalizedString("KeyIsVerified", comment: "The Key is verified. The time when the Key was verified") + "\(keyWrapper?.verifyTime)"
                 return cell
             }
-                else if toRowType(indexPath) == .Revoked {
-                let cell = tableView.dequeueReusableCellWithIdentifier("RevokedCell")!
+                else if toRowType(indexPath) == .revoked {
+                let cell = tableView.dequeueReusableCell(withIdentifier: "RevokedCell")!
                 cell.textLabel?.text = NSLocalizedString("KeyIsRevoked", comment: "The Key is revoked. The time when the Key was revoked") + "\(keyWrapper?.revokeTime)"
                 return cell
             }
         }
 
-            else if toSectionType(indexPath.section) == .Addresses {
-            let cell = tableView.dequeueReusableCellWithIdentifier("MailAddressCell")!
+            else if toSectionType(indexPath.section) == .addresses {
+            let cell = tableView.dequeueReusableCell(withIdentifier: "MailAddressCell")!
             if let addr = keyWrapper?.mailAddressesInKey?[indexPath.row] {
                 for ourAddr in (keyWrapper?.mailAddresses)! {
-                    if addr.containsString(ourAddr) {
-                        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
+                    if addr.contains(ourAddr) {
+                        cell.accessoryType = UITableViewCellAccessoryType.checkmark
                         break
                     }
                 }
@@ -109,22 +109,22 @@ extension KeyViewController: UITableViewDataSource {
             return cell
         }
 
-        let cell = tableView.dequeueReusableCellWithIdentifier("VerifiedCell")!
+        let cell = tableView.dequeueReusableCell(withIdentifier: "VerifiedCell")!
         cell.textLabel?.text = NSLocalizedString("KeyNotFound", comment: "there was no key found. Contact developers")
         return cell
     }
     
-    func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
+    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
         if section == 1 {
             return NSLocalizedString("Checkmarks", comment: "Checkmarks")
         }
         return nil
     }
 
-    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+    func numberOfSections(in tableView: UITableView) -> Int {
         if let key = keyWrapper {
             var sections = 1
-            if let addrs = key.mailAddresses where addrs != [] {
+            if let addrs = key.mailAddresses, addrs != [] {
                 sections += 1
             }
             return sections
@@ -132,34 +132,34 @@ extension KeyViewController: UITableViewDataSource {
         return 1
     }
 
-    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
-        if toSectionType(section) == .KeyDetails {
+    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
+        if toSectionType(section) == .keyDetails {
             return NSLocalizedString("KeyDetails", comment: "Details of the key")
         }
-        if toSectionType(section) == .Addresses {
+        if toSectionType(section) == .addresses {
             return NSLocalizedString("KeyAddresses", comment: "Mailaddresses Connected to the key")
         }
         return nil
     }
 
-    func toSectionType(sectionNumber: Int) -> KeyViewSectionType {
-        var returnValue: KeyViewSectionType = .NoKey
+    func toSectionType(_ sectionNumber: Int) -> KeyViewSectionType {
+        var returnValue: KeyViewSectionType = .noKey
 
         if keyWrapper != nil {
-            returnValue = .KeyDetails//.KeyID
+            returnValue = .keyDetails//.KeyID
             //addresses
             if sectionNumber != 0 {
-                returnValue = .Addresses
+                returnValue = .addresses
             }
         }
         return returnValue
     }
 
-    func toRowType(index: NSIndexPath) -> KeyViewRowType {
-        var returnValue: KeyViewRowType = .NoKey
+    func toRowType(_ index: IndexPath) -> KeyViewRowType {
+        var returnValue: KeyViewRowType = .noKey
         var row = index.row
-        if let key = keyWrapper where toSectionType(index.section) == .KeyDetails {
-            returnValue = .KeyID
+        if let key = keyWrapper, toSectionType(index.section) == .keyDetails {
+            returnValue = .keyID
             //EncryptionType
             if row != 0 {
                 returnValue = KeyViewRowType(rawValue: returnValue.rawValue + 1)!
@@ -187,7 +187,7 @@ extension KeyViewController: UITableViewDataSource {
             }
             //too much rows
             if row != 0 {
-                returnValue = .NoKey
+                returnValue = .noKey
             }
         }
         return returnValue
@@ -199,9 +199,9 @@ extension KeyViewController: UITableViewDelegate {
 }
 
 enum KeyViewSectionType: Int {
-    case NoKey = 0, KeyDetails, Addresses
+    case noKey = 0, keyDetails, addresses
 }
 
 enum KeyViewRowType: Int {
-    case NoKey = 0, KeyID, EncryptionType, DiscoveryTime, DiscoveryMail, Verified, Revoked
+    case noKey = 0, keyID, encryptionType, discoveryTime, discoveryMail, verified, revoked
 }
diff --git a/enzevalos_iphone/KeyWrapper.swift b/enzevalos_iphone/KeyWrapper.swift
index 699d1df7c9fe938f68bf48d5c0c931a31b521399..e7a9781ad7d9bf7019280373057b5e170f41664b 100644
--- a/enzevalos_iphone/KeyWrapper.swift
+++ b/enzevalos_iphone/KeyWrapper.swift
@@ -11,16 +11,16 @@ import Foundation
 public protocol KeyWrapper {
     
     var revoked: Bool {get set}
-    var revokeTime: NSDate? {get}
+    var revokeTime: Date? {get}
     var trustlevel: Int {get set}
     var verified: Bool {get set}
-    var verifyTime: NSDate? {get}
-    var discoveryTime: NSDate {get}
+    var verifyTime: Date? {get}
+    var discoveryTime: Date {get}
     var discoveryMailUID: UInt64? {get}
     var type: EncryptionType {get}
     var keyID: String {get}
-    var creationDate: NSDate {get}
-    var expireDate: NSDate? {get}
+    var creationDate: Date {get}
+    var expireDate: Date? {get}
     
     //Mailaddresses we discovered using this key
     var mailAddresses: [String]? {get set}
@@ -30,5 +30,5 @@ public protocol KeyWrapper {
     
     init(coder: NSCoder)
     
-    func encodeWithCoder(coder: NSCoder)
+    func encodeWithCoder(_ coder: NSCoder)
 }
diff --git a/enzevalos_iphone/LabelStyleKit.swift b/enzevalos_iphone/LabelStyleKit.swift
index 82ff02a203cd7b06fa0f11f46bb629211b86ad9a..dd44646481fb23d9d7b951c6a02136c63aa81242 100644
--- a/enzevalos_iphone/LabelStyleKit.swift
+++ b/enzevalos_iphone/LabelStyleKit.swift
@@ -15,12 +15,12 @@
 
 import UIKit
 
-public class LabelStyleKit : NSObject {
+open class LabelStyleKit : NSObject {
 
     //// Cache
 
-    private struct Cache {
-        static let black: UIColor = UIColor.blackColor()
+    fileprivate struct Cache {
+        static let black: UIColor = UIColor.black
         static var imageOfHome: UIImage?
         static var homeTargets: [AnyObject]?
         static var imageOfWork: UIImage?
@@ -31,173 +31,173 @@ public class LabelStyleKit : NSObject {
 
     //// Colors
 
-    public dynamic class var black: UIColor { return Cache.black }
+    open dynamic class var black: UIColor { return Cache.black }
 
     //// Drawing Methods
 
-    public dynamic class func drawHome(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 28, height: 28), resizing: ResizingBehavior = .AspectFit, color: UIColor = LabelStyleKit.black) {
+    open dynamic class func drawHome(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 28, height: 28), resizing: ResizingBehavior = .aspectFit, color: UIColor = LabelStyleKit.black) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 28, height: 28), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 28, resizedFrame.height / 28)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 28, y: resizedFrame.height / 28)
 
 
         //// Bezier Drawing
         let bezierPath = UIBezierPath()
-        bezierPath.moveToPoint(CGPoint(x: 21.2, y: 13))
-        bezierPath.addLineToPoint(CGPoint(x: 7.1, y: 13))
-        bezierPath.addCurveToPoint(CGPoint(x: 4.3, y: 15.8), controlPoint1: CGPoint(x: 5.5, y: 13), controlPoint2: CGPoint(x: 4.3, y: 14.3))
-        bezierPath.addLineToPoint(CGPoint(x: 4.3, y: 24.6))
-        bezierPath.addCurveToPoint(CGPoint(x: 7.1, y: 27.4), controlPoint1: CGPoint(x: 4.3, y: 26.2), controlPoint2: CGPoint(x: 5.6, y: 27.4))
-        bezierPath.addLineToPoint(CGPoint(x: 21.2, y: 27.4))
-        bezierPath.addCurveToPoint(CGPoint(x: 24, y: 24.6), controlPoint1: CGPoint(x: 22.8, y: 27.4), controlPoint2: CGPoint(x: 24, y: 26.1))
-        bezierPath.addLineToPoint(CGPoint(x: 24, y: 15.8))
-        bezierPath.addCurveToPoint(CGPoint(x: 21.2, y: 13), controlPoint1: CGPoint(x: 24.1, y: 14.3), controlPoint2: CGPoint(x: 22.8, y: 13))
-        bezierPath.closePath()
+        bezierPath.move(to: CGPoint(x: 21.2, y: 13))
+        bezierPath.addLine(to: CGPoint(x: 7.1, y: 13))
+        bezierPath.addCurve(to: CGPoint(x: 4.3, y: 15.8), controlPoint1: CGPoint(x: 5.5, y: 13), controlPoint2: CGPoint(x: 4.3, y: 14.3))
+        bezierPath.addLine(to: CGPoint(x: 4.3, y: 24.6))
+        bezierPath.addCurve(to: CGPoint(x: 7.1, y: 27.4), controlPoint1: CGPoint(x: 4.3, y: 26.2), controlPoint2: CGPoint(x: 5.6, y: 27.4))
+        bezierPath.addLine(to: CGPoint(x: 21.2, y: 27.4))
+        bezierPath.addCurve(to: CGPoint(x: 24, y: 24.6), controlPoint1: CGPoint(x: 22.8, y: 27.4), controlPoint2: CGPoint(x: 24, y: 26.1))
+        bezierPath.addLine(to: CGPoint(x: 24, y: 15.8))
+        bezierPath.addCurve(to: CGPoint(x: 21.2, y: 13), controlPoint1: CGPoint(x: 24.1, y: 14.3), controlPoint2: CGPoint(x: 22.8, y: 13))
+        bezierPath.close()
         color.setFill()
         bezierPath.fill()
 
 
         //// Bezier 2 Drawing
         let bezier2Path = UIBezierPath()
-        bezier2Path.moveToPoint(CGPoint(x: 14.3, y: 2.4))
-        bezier2Path.addLineToPoint(CGPoint(x: 25.8, y: 14.2))
-        bezier2Path.addLineToPoint(CGPoint(x: 2.5, y: 14.2))
-        bezier2Path.addLineToPoint(CGPoint(x: 14.3, y: 2.4))
-        bezier2Path.closePath()
+        bezier2Path.move(to: CGPoint(x: 14.3, y: 2.4))
+        bezier2Path.addLine(to: CGPoint(x: 25.8, y: 14.2))
+        bezier2Path.addLine(to: CGPoint(x: 2.5, y: 14.2))
+        bezier2Path.addLine(to: CGPoint(x: 14.3, y: 2.4))
+        bezier2Path.close()
         color.setFill()
         bezier2Path.fill()
         color.setStroke()
         bezier2Path.lineWidth = 3
-        bezier2Path.lineJoinStyle = .Round
+        bezier2Path.lineJoinStyle = .round
         bezier2Path.stroke()
 
 
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 21.9, y: 10.6))
-        bezier3Path.addLineToPoint(CGPoint(x: 20.8, y: 10.6))
-        bezier3Path.addCurveToPoint(CGPoint(x: 19.9, y: 9.7), controlPoint1: CGPoint(x: 20.3, y: 10.6), controlPoint2: CGPoint(x: 19.9, y: 10.2))
-        bezier3Path.addLineToPoint(CGPoint(x: 19.9, y: 4.7))
-        bezier3Path.addCurveToPoint(CGPoint(x: 20.8, y: 3.8), controlPoint1: CGPoint(x: 19.9, y: 4.2), controlPoint2: CGPoint(x: 20.3, y: 3.8))
-        bezier3Path.addLineToPoint(CGPoint(x: 21.9, y: 3.8))
-        bezier3Path.addCurveToPoint(CGPoint(x: 22.8, y: 4.7), controlPoint1: CGPoint(x: 22.4, y: 3.8), controlPoint2: CGPoint(x: 22.8, y: 4.2))
-        bezier3Path.addLineToPoint(CGPoint(x: 22.8, y: 9.8))
-        bezier3Path.addCurveToPoint(CGPoint(x: 21.9, y: 10.6), controlPoint1: CGPoint(x: 22.7, y: 10.2), controlPoint2: CGPoint(x: 22.3, y: 10.6))
-        bezier3Path.closePath()
+        bezier3Path.move(to: CGPoint(x: 21.9, y: 10.6))
+        bezier3Path.addLine(to: CGPoint(x: 20.8, y: 10.6))
+        bezier3Path.addCurve(to: CGPoint(x: 19.9, y: 9.7), controlPoint1: CGPoint(x: 20.3, y: 10.6), controlPoint2: CGPoint(x: 19.9, y: 10.2))
+        bezier3Path.addLine(to: CGPoint(x: 19.9, y: 4.7))
+        bezier3Path.addCurve(to: CGPoint(x: 20.8, y: 3.8), controlPoint1: CGPoint(x: 19.9, y: 4.2), controlPoint2: CGPoint(x: 20.3, y: 3.8))
+        bezier3Path.addLine(to: CGPoint(x: 21.9, y: 3.8))
+        bezier3Path.addCurve(to: CGPoint(x: 22.8, y: 4.7), controlPoint1: CGPoint(x: 22.4, y: 3.8), controlPoint2: CGPoint(x: 22.8, y: 4.2))
+        bezier3Path.addLine(to: CGPoint(x: 22.8, y: 9.8))
+        bezier3Path.addCurve(to: CGPoint(x: 21.9, y: 10.6), controlPoint1: CGPoint(x: 22.7, y: 10.2), controlPoint2: CGPoint(x: 22.3, y: 10.6))
+        bezier3Path.close()
         color.setFill()
         bezier3Path.fill()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
 
-    public dynamic class func drawWork(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 148, height: 134), resizing: ResizingBehavior = .AspectFit, color: UIColor = LabelStyleKit.black) {
+    open dynamic class func drawWork(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 148, height: 134), resizing: ResizingBehavior = .aspectFit, color: UIColor = LabelStyleKit.black) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 148, height: 134), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 148, resizedFrame.height / 134)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 148, y: resizedFrame.height / 134)
 
 
         //// Bezier 3 Drawing
         let bezier3Path = UIBezierPath()
-        bezier3Path.moveToPoint(CGPoint(x: 79.9, y: 72.4))
-        bezier3Path.addLineToPoint(CGPoint(x: 79.9, y: 76.5))
-        bezier3Path.addCurveToPoint(CGPoint(x: 73.5, y: 82.9), controlPoint1: CGPoint(x: 79.9, y: 80), controlPoint2: CGPoint(x: 77, y: 82.9))
-        bezier3Path.addLineToPoint(CGPoint(x: 73.5, y: 82.9))
-        bezier3Path.addCurveToPoint(CGPoint(x: 67.1, y: 76.5), controlPoint1: CGPoint(x: 70, y: 82.9), controlPoint2: CGPoint(x: 67.1, y: 80))
-        bezier3Path.addLineToPoint(CGPoint(x: 67.1, y: 72.2))
-        bezier3Path.addCurveToPoint(CGPoint(x: 2.8, y: 63), controlPoint1: CGPoint(x: 29.8, y: 71), controlPoint2: CGPoint(x: 3.2, y: 63.2))
-        bezier3Path.addLineToPoint(CGPoint(x: 2.8, y: 119))
-        bezier3Path.addCurveToPoint(CGPoint(x: 14.8, y: 131), controlPoint1: CGPoint(x: 2.8, y: 125.6), controlPoint2: CGPoint(x: 8.2, y: 131))
-        bezier3Path.addLineToPoint(CGPoint(x: 132.8, y: 131))
-        bezier3Path.addCurveToPoint(CGPoint(x: 144.8, y: 119), controlPoint1: CGPoint(x: 139.4, y: 131), controlPoint2: CGPoint(x: 144.8, y: 125.6))
-        bezier3Path.addLineToPoint(CGPoint(x: 144.8, y: 63))
-        bezier3Path.addCurveToPoint(CGPoint(x: 79.9, y: 72.4), controlPoint1: CGPoint(x: 122.2, y: 69.9), controlPoint2: CGPoint(x: 100.3, y: 72.2))
-        bezier3Path.closePath()
+        bezier3Path.move(to: CGPoint(x: 79.9, y: 72.4))
+        bezier3Path.addLine(to: CGPoint(x: 79.9, y: 76.5))
+        bezier3Path.addCurve(to: CGPoint(x: 73.5, y: 82.9), controlPoint1: CGPoint(x: 79.9, y: 80), controlPoint2: CGPoint(x: 77, y: 82.9))
+        bezier3Path.addLine(to: CGPoint(x: 73.5, y: 82.9))
+        bezier3Path.addCurve(to: CGPoint(x: 67.1, y: 76.5), controlPoint1: CGPoint(x: 70, y: 82.9), controlPoint2: CGPoint(x: 67.1, y: 80))
+        bezier3Path.addLine(to: CGPoint(x: 67.1, y: 72.2))
+        bezier3Path.addCurve(to: CGPoint(x: 2.8, y: 63), controlPoint1: CGPoint(x: 29.8, y: 71), controlPoint2: CGPoint(x: 3.2, y: 63.2))
+        bezier3Path.addLine(to: CGPoint(x: 2.8, y: 119))
+        bezier3Path.addCurve(to: CGPoint(x: 14.8, y: 131), controlPoint1: CGPoint(x: 2.8, y: 125.6), controlPoint2: CGPoint(x: 8.2, y: 131))
+        bezier3Path.addLine(to: CGPoint(x: 132.8, y: 131))
+        bezier3Path.addCurve(to: CGPoint(x: 144.8, y: 119), controlPoint1: CGPoint(x: 139.4, y: 131), controlPoint2: CGPoint(x: 144.8, y: 125.6))
+        bezier3Path.addLine(to: CGPoint(x: 144.8, y: 63))
+        bezier3Path.addCurve(to: CGPoint(x: 79.9, y: 72.4), controlPoint1: CGPoint(x: 122.2, y: 69.9), controlPoint2: CGPoint(x: 100.3, y: 72.2))
+        bezier3Path.close()
         color.setFill()
         bezier3Path.fill()
 
 
         //// Bezier 4 Drawing
         let bezier4Path = UIBezierPath()
-        bezier4Path.moveToPoint(CGPoint(x: 132.8, y: 28.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 102.3, y: 28.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 102.3, y: 24.1))
-        bezier4Path.addCurveToPoint(CGPoint(x: 81.9, y: 3.8), controlPoint1: CGPoint(x: 102.3, y: 12.9), controlPoint2: CGPoint(x: 93.2, y: 3.8))
-        bezier4Path.addLineToPoint(CGPoint(x: 65.8, y: 3.8))
-        bezier4Path.addCurveToPoint(CGPoint(x: 45.4, y: 24.1), controlPoint1: CGPoint(x: 54.6, y: 3.8), controlPoint2: CGPoint(x: 45.4, y: 12.9))
-        bezier4Path.addLineToPoint(CGPoint(x: 45.4, y: 28.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 14.8, y: 28.1))
-        bezier4Path.addCurveToPoint(CGPoint(x: 2.8, y: 40.1), controlPoint1: CGPoint(x: 8.2, y: 28.1), controlPoint2: CGPoint(x: 2.8, y: 33.5))
-        bezier4Path.addLineToPoint(CGPoint(x: 2.8, y: 57.7))
-        bezier4Path.addCurveToPoint(CGPoint(x: 67.1, y: 66.9), controlPoint1: CGPoint(x: 3.2, y: 57.8), controlPoint2: CGPoint(x: 30.3, y: 65.7))
-        bezier4Path.addLineToPoint(CGPoint(x: 67.1, y: 63.6))
-        bezier4Path.addCurveToPoint(CGPoint(x: 73.5, y: 57.2), controlPoint1: CGPoint(x: 67.1, y: 60.1), controlPoint2: CGPoint(x: 70, y: 57.2))
-        bezier4Path.addLineToPoint(CGPoint(x: 73.5, y: 57.2))
-        bezier4Path.addCurveToPoint(CGPoint(x: 79.9, y: 63.6), controlPoint1: CGPoint(x: 77, y: 57.2), controlPoint2: CGPoint(x: 79.9, y: 60.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 79.9, y: 67))
-        bezier4Path.addCurveToPoint(CGPoint(x: 144.9, y: 57.6), controlPoint1: CGPoint(x: 100.2, y: 66.8), controlPoint2: CGPoint(x: 122.7, y: 64.4))
-        bezier4Path.addLineToPoint(CGPoint(x: 144.9, y: 40.1))
-        bezier4Path.addCurveToPoint(CGPoint(x: 132.8, y: 28.1), controlPoint1: CGPoint(x: 144.8, y: 33.5), controlPoint2: CGPoint(x: 139.5, y: 28.1))
-        bezier4Path.closePath()
-        bezier4Path.moveToPoint(CGPoint(x: 91.7, y: 28.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 56.1, y: 28.1))
-        bezier4Path.addLineToPoint(CGPoint(x: 56.1, y: 24.1))
-        bezier4Path.addCurveToPoint(CGPoint(x: 65.8, y: 14.4), controlPoint1: CGPoint(x: 56.1, y: 18.7), controlPoint2: CGPoint(x: 60.5, y: 14.4))
-        bezier4Path.addLineToPoint(CGPoint(x: 82, y: 14.4))
-        bezier4Path.addCurveToPoint(CGPoint(x: 91.7, y: 24.1), controlPoint1: CGPoint(x: 87.4, y: 14.4), controlPoint2: CGPoint(x: 91.7, y: 18.8))
-        bezier4Path.addLineToPoint(CGPoint(x: 91.7, y: 28.1))
-        bezier4Path.closePath()
+        bezier4Path.move(to: CGPoint(x: 132.8, y: 28.1))
+        bezier4Path.addLine(to: CGPoint(x: 102.3, y: 28.1))
+        bezier4Path.addLine(to: CGPoint(x: 102.3, y: 24.1))
+        bezier4Path.addCurve(to: CGPoint(x: 81.9, y: 3.8), controlPoint1: CGPoint(x: 102.3, y: 12.9), controlPoint2: CGPoint(x: 93.2, y: 3.8))
+        bezier4Path.addLine(to: CGPoint(x: 65.8, y: 3.8))
+        bezier4Path.addCurve(to: CGPoint(x: 45.4, y: 24.1), controlPoint1: CGPoint(x: 54.6, y: 3.8), controlPoint2: CGPoint(x: 45.4, y: 12.9))
+        bezier4Path.addLine(to: CGPoint(x: 45.4, y: 28.1))
+        bezier4Path.addLine(to: CGPoint(x: 14.8, y: 28.1))
+        bezier4Path.addCurve(to: CGPoint(x: 2.8, y: 40.1), controlPoint1: CGPoint(x: 8.2, y: 28.1), controlPoint2: CGPoint(x: 2.8, y: 33.5))
+        bezier4Path.addLine(to: CGPoint(x: 2.8, y: 57.7))
+        bezier4Path.addCurve(to: CGPoint(x: 67.1, y: 66.9), controlPoint1: CGPoint(x: 3.2, y: 57.8), controlPoint2: CGPoint(x: 30.3, y: 65.7))
+        bezier4Path.addLine(to: CGPoint(x: 67.1, y: 63.6))
+        bezier4Path.addCurve(to: CGPoint(x: 73.5, y: 57.2), controlPoint1: CGPoint(x: 67.1, y: 60.1), controlPoint2: CGPoint(x: 70, y: 57.2))
+        bezier4Path.addLine(to: CGPoint(x: 73.5, y: 57.2))
+        bezier4Path.addCurve(to: CGPoint(x: 79.9, y: 63.6), controlPoint1: CGPoint(x: 77, y: 57.2), controlPoint2: CGPoint(x: 79.9, y: 60.1))
+        bezier4Path.addLine(to: CGPoint(x: 79.9, y: 67))
+        bezier4Path.addCurve(to: CGPoint(x: 144.9, y: 57.6), controlPoint1: CGPoint(x: 100.2, y: 66.8), controlPoint2: CGPoint(x: 122.7, y: 64.4))
+        bezier4Path.addLine(to: CGPoint(x: 144.9, y: 40.1))
+        bezier4Path.addCurve(to: CGPoint(x: 132.8, y: 28.1), controlPoint1: CGPoint(x: 144.8, y: 33.5), controlPoint2: CGPoint(x: 139.5, y: 28.1))
+        bezier4Path.close()
+        bezier4Path.move(to: CGPoint(x: 91.7, y: 28.1))
+        bezier4Path.addLine(to: CGPoint(x: 56.1, y: 28.1))
+        bezier4Path.addLine(to: CGPoint(x: 56.1, y: 24.1))
+        bezier4Path.addCurve(to: CGPoint(x: 65.8, y: 14.4), controlPoint1: CGPoint(x: 56.1, y: 18.7), controlPoint2: CGPoint(x: 60.5, y: 14.4))
+        bezier4Path.addLine(to: CGPoint(x: 82, y: 14.4))
+        bezier4Path.addCurve(to: CGPoint(x: 91.7, y: 24.1), controlPoint1: CGPoint(x: 87.4, y: 14.4), controlPoint2: CGPoint(x: 91.7, y: 18.8))
+        bezier4Path.addLine(to: CGPoint(x: 91.7, y: 28.1))
+        bezier4Path.close()
         color.setFill()
         bezier4Path.fill()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
 
-    public dynamic class func drawOther(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 86, height: 82), resizing: ResizingBehavior = .AspectFit, color: UIColor = LabelStyleKit.black) {
+    open dynamic class func drawOther(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 86, height: 82), resizing: ResizingBehavior = .aspectFit, color: UIColor = LabelStyleKit.black) {
         //// General Declarations
         let context = UIGraphicsGetCurrentContext()!
         
         //// Resize to Target Frame
-        CGContextSaveGState(context)
+        context.saveGState()
         let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 86, height: 82), target: targetFrame)
-        CGContextTranslateCTM(context, resizedFrame.minX, resizedFrame.minY)
-        CGContextScaleCTM(context, resizedFrame.width / 86, resizedFrame.height / 82)
+        context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
+        context.scaleBy(x: resizedFrame.width / 86, y: resizedFrame.height / 82)
 
 
         //// Star Drawing
         let starPath = UIBezierPath()
-        starPath.moveToPoint(CGPoint(x: 43, y: 1))
-        starPath.addLineToPoint(CGPoint(x: 55.19, y: 28.22))
-        starPath.addLineToPoint(CGPoint(x: 84.85, y: 31.4))
-        starPath.addLineToPoint(CGPoint(x: 62.73, y: 51.41))
-        starPath.addLineToPoint(CGPoint(x: 68.86, y: 80.6))
-        starPath.addLineToPoint(CGPoint(x: 43, y: 65.75))
-        starPath.addLineToPoint(CGPoint(x: 17.14, y: 80.6))
-        starPath.addLineToPoint(CGPoint(x: 23.27, y: 51.41))
-        starPath.addLineToPoint(CGPoint(x: 1.15, y: 31.4))
-        starPath.addLineToPoint(CGPoint(x: 30.81, y: 28.22))
-        starPath.closePath()
+        starPath.move(to: CGPoint(x: 43, y: 1))
+        starPath.addLine(to: CGPoint(x: 55.19, y: 28.22))
+        starPath.addLine(to: CGPoint(x: 84.85, y: 31.4))
+        starPath.addLine(to: CGPoint(x: 62.73, y: 51.41))
+        starPath.addLine(to: CGPoint(x: 68.86, y: 80.6))
+        starPath.addLine(to: CGPoint(x: 43, y: 65.75))
+        starPath.addLine(to: CGPoint(x: 17.14, y: 80.6))
+        starPath.addLine(to: CGPoint(x: 23.27, y: 51.41))
+        starPath.addLine(to: CGPoint(x: 1.15, y: 31.4))
+        starPath.addLine(to: CGPoint(x: 30.81, y: 28.22))
+        starPath.close()
         color.setFill()
         starPath.fill()
         
-        CGContextRestoreGState(context)
+        context.restoreGState()
 
     }
 
     //// Generated Images
 
-    public dynamic class var imageOfHome: UIImage {
+    open dynamic class var imageOfHome: UIImage {
         if Cache.imageOfHome != nil {
             return Cache.imageOfHome!
         }
@@ -211,7 +211,7 @@ public class LabelStyleKit : NSObject {
         return Cache.imageOfHome!
     }
 
-    public dynamic class var imageOfWork: UIImage {
+    open dynamic class var imageOfWork: UIImage {
         if Cache.imageOfWork != nil {
             return Cache.imageOfWork!
         }
@@ -225,7 +225,7 @@ public class LabelStyleKit : NSObject {
         return Cache.imageOfWork!
     }
 
-    public dynamic class var imageOfOther: UIImage {
+    open dynamic class var imageOfOther: UIImage {
         if Cache.imageOfOther != nil {
             return Cache.imageOfOther!
         }
@@ -246,7 +246,7 @@ public class LabelStyleKit : NSObject {
         set {
             Cache.homeTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: LabelStyleKit.imageOfHome)
+                target.perform(NSSelectorFromString("setImage:"), with: LabelStyleKit.imageOfHome)
             }
         }
     }
@@ -256,7 +256,7 @@ public class LabelStyleKit : NSObject {
         set {
             Cache.workTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: LabelStyleKit.imageOfWork)
+                target.perform(NSSelectorFromString("setImage:"), with: LabelStyleKit.imageOfWork)
             }
         }
     }
@@ -266,7 +266,7 @@ public class LabelStyleKit : NSObject {
         set {
             Cache.otherTargets = newValue
             for target: AnyObject in newValue {
-                target.performSelector(NSSelectorFromString("setImage:"), withObject: LabelStyleKit.imageOfOther)
+                target.perform(NSSelectorFromString("setImage:"), with: LabelStyleKit.imageOfOther)
             }
         }
     }
@@ -275,12 +275,12 @@ public class LabelStyleKit : NSObject {
 
 
     @objc public enum ResizingBehavior: Int {
-        case AspectFit /// The content is proportionally resized to fit into the target rectangle.
-        case AspectFill /// The content is proportionally resized to completely fill the target rectangle.
-        case Stretch /// The content is stretched to match the entire target rectangle.
-        case Center /// The content is centered in the target rectangle, but it is NOT resized.
+        case aspectFit /// The content is proportionally resized to fit into the target rectangle.
+        case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
+        case stretch /// The content is stretched to match the entire target rectangle.
+        case center /// The content is centered in the target rectangle, but it is NOT resized.
 
-        public func apply(rect rect: CGRect, target: CGRect) -> CGRect {
+        public func apply(rect: CGRect, target: CGRect) -> CGRect {
             if rect == target || target == CGRect.zero {
                 return rect
             }
@@ -290,15 +290,15 @@ public class LabelStyleKit : NSObject {
             scales.height = abs(target.height / rect.height)
 
             switch self {
-                case .AspectFit:
+                case .aspectFit:
                     scales.width = min(scales.width, scales.height)
                     scales.height = scales.width
-                case .AspectFill:
+                case .aspectFill:
                     scales.width = max(scales.width, scales.height)
                     scales.height = scales.width
-                case .Stretch:
+                case .stretch:
                     break
-                case .Center:
+                case .center:
                     scales.width = 1
                     scales.height = 1
             }
diff --git a/enzevalos_iphone/ListViewController.swift b/enzevalos_iphone/ListViewController.swift
index 7574df4d155def6ef3f3294d55a67b606389f79e..28c7a4cc1d717b879065d1d4d32b4f5cea7d95b1 100644
--- a/enzevalos_iphone/ListViewController.swift
+++ b/enzevalos_iphone/ListViewController.swift
@@ -8,6 +8,41 @@
 
 import UIKit
 import Foundation
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l < r
+  case (nil, _?):
+    return true
+  default:
+    return false
+  }
+}
+
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l > r
+  default:
+    return rhs < lhs
+  }
+}
+
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l >= r
+  default:
+    return !(lhs < rhs)
+  }
+}
+
 
 class ListViewController: UITableViewController {
     let searchController = UISearchController(searchResultsController: nil)
@@ -23,7 +58,7 @@ class ListViewController: UITableViewController {
     }
     var loading = false
 
-    override func viewWillAppear(animated: Bool) {
+    override func viewWillAppear(_ animated: Bool) {
         tableView.reloadData()
     }
 
@@ -36,10 +71,10 @@ class ListViewController: UITableViewController {
         searchController.searchBar.scopeButtonTitles = [NSLocalizedString("Subject", comment: ""), NSLocalizedString("Body", comment: ""), NSLocalizedString("CC", comment: ""), NSLocalizedString("All", comment: "")]
         searchController.searchBar.delegate = self
 
-        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
+        tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableViewScrollPosition.top, animated: false)
     }
 
-    func doneLoading(error: Bool) {
+    func doneLoading(_ error: Bool) {
         if error {
             // TODO: maybe we should do something about this? maybe not?
         }
@@ -52,25 +87,25 @@ class ListViewController: UITableViewController {
         tableView.reloadData()
     }
 
-    func filterContentForSearchText(searchText: String, scope: Int = 0) {
+    func filterContentForSearchText(_ searchText: String, scope: Int = 0) {
         filteredMails = contact!.mails.filter { mail in
             var returnValue = false
             switch scope {
             case 0:
                 if let subject = mail.subject {
-                    returnValue = subject.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = subject.lowercased().contains(searchText.lowercased())
                 }
             case 1:
                 if !returnValue && mail.decryptedBody != nil {
-                    returnValue = mail.decryptedBody!.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = mail.decryptedBody!.lowercased().contains(searchText.lowercased())
                 } else if !returnValue && mail.body != nil {
-                    returnValue = mail.body!.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = mail.body!.lowercased().contains(searchText.lowercased())
                 }
             case 2:
                 if !returnValue && mail.cc?.count > 0 {
-                    if let result = mail.cc?.contains({ cc -> Bool in
+                    if let result = mail.cc?.contains(where: { cc -> Bool in
                         if let mail = cc as? MailAddress {
-                            return mail.mailAddress.containsString(searchText.lowercaseString)
+                            return mail.mailAddress.contains(searchText.lowercased())
                         }
                         return false
                     }) {
@@ -78,23 +113,23 @@ class ListViewController: UITableViewController {
                     }
                 }
                 if !returnValue && mail.getReceivers().count > 1 {
-                    returnValue = mail.getReceivers().contains({ rec -> Bool in
-                        return rec.mailAddress.containsString(searchText.lowercaseString)
+                    returnValue = mail.getReceivers().contains(where: { rec -> Bool in
+                        return rec.mailAddress.contains(searchText.lowercased())
                     })
                 }
             default:
                 if let subject = mail.subject {
-                    returnValue = subject.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = subject.lowercased().contains(searchText.lowercased())
                 }
                 if !returnValue && mail.decryptedBody != nil {
-                    returnValue = mail.decryptedBody!.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = mail.decryptedBody!.lowercased().contains(searchText.lowercased())
                 } else if !returnValue && mail.body != nil {
-                    returnValue = mail.body!.lowercaseString.containsString(searchText.lowercaseString)
+                    returnValue = mail.body!.lowercased().contains(searchText.lowercased())
                 }
                 if !returnValue && mail.cc?.count > 0 {
-                    if let res = mail.cc?.contains({ cc -> Bool in
+                    if let res = mail.cc?.contains(where: { cc -> Bool in
                         if let mail = cc as? MailAddress {
-                            return mail.mailAddress.containsString(searchText.lowercaseString)
+                            return mail.mailAddress.contains(searchText.lowercased())
                         }
                         return false
                     }) {
@@ -102,8 +137,8 @@ class ListViewController: UITableViewController {
                     }
                 }
                 if !returnValue && mail.getReceivers().count > 1 {
-                    returnValue = mail.getReceivers().contains({ rec -> Bool in
-                        return rec.mailAddress.containsString(searchText.lowercaseString)
+                    returnValue = mail.getReceivers().contains(where: { rec -> Bool in
+                        return rec.mailAddress.contains(searchText.lowercased())
                     })
                 }
             }
@@ -113,8 +148,8 @@ class ListViewController: UITableViewController {
         tableView.reloadData()
     }
 
-    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-        if searchController.active && searchController.searchBar.text != "" {
+    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+        if searchController.isActive && searchController.searchBar.text != "" {
             return filteredMails.count
         }
         if let count = contact?.mails.count {
@@ -124,47 +159,47 @@ class ListViewController: UITableViewController {
         }
     }
 
-    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
+    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let mail: Mail?
 
-        if searchController.active && searchController.searchBar.text != "" {
+        if searchController.isActive && searchController.searchBar.text != "" {
             mail = filteredMails[indexPath.row]
         } else if indexPath.row >= contact?.mails.count {
-            let cell = tableView.dequeueReusableCellWithIdentifier("LoadingCell")
+            let cell = tableView.dequeueReusableCell(withIdentifier: "LoadingCell")
             return cell!
         } else {
             mail = contact?.mails[indexPath.row]
         }
 
-        let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! ListViewCell!
+        let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell") as! ListViewCell!
 
         if mail != nil && !mail!.isRead {
-            cell.subjectLabel.font = UIFont.boldSystemFontOfSize(17.0)
+            cell?.subjectLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
         } else {
-            cell.subjectLabel.font = UIFont.systemFontOfSize(17.0)
+            cell?.subjectLabel.font = UIFont.systemFont(ofSize: 17.0)
         }
-        cell.subjectLabel.text = mail?.getSubjectWithFlagsString()
-        cell.bodyLabel.text = mail?.shortBodyString
-        cell.dateLabel.text = mail?.timeString
+        cell?.subjectLabel.text = mail?.getSubjectWithFlagsString()
+        cell?.bodyLabel.text = mail?.shortBodyString
+        cell?.dateLabel.text = mail?.timeString
 
-        return cell
+        return cell!
     }
 
-    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
+    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let mail: Mail?
 
-        if searchController.active && searchController.searchBar.text != "" {
+        if searchController.isActive && searchController.searchBar.text != "" {
             mail = filteredMails[indexPath.row]
         } else if indexPath.row >= contact?.mails.count {
-            tableView.deselectRowAtIndexPath(indexPath, animated: true)
+            tableView.deselectRow(at: indexPath, animated: true)
             return
         } else {
             mail = contact?.mails[indexPath.row]
         }
-        performSegueWithIdentifier("readMailSegue", sender: mail)
+        performSegue(withIdentifier: "readMailSegue", sender: mail)
     }
 
-    override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
+    override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
         let offset = scrollView.contentOffset
         let bounds = scrollView.bounds
         let size = scrollView.contentSize
@@ -181,10 +216,10 @@ class ListViewController: UITableViewController {
         }
     }
 
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "readMailSegue" {
             if let mail = sender as? Mail {
-                let DestinationViewController: ReadViewController = segue.destinationViewController as! ReadViewController
+                let DestinationViewController: ReadViewController = segue.destination as! ReadViewController
                 DestinationViewController.mail = mail
             }
         }
@@ -192,7 +227,7 @@ class ListViewController: UITableViewController {
 }
 
 extension ListViewController: UISearchResultsUpdating {
-    func updateSearchResultsForSearchController(searchController: UISearchController) {
+    func updateSearchResults(for searchController: UISearchController) {
         let searchBar = searchController.searchBar
         let _ = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
         filterContentForSearchText(searchController.searchBar.text!, scope: searchBar.selectedScopeButtonIndex)
@@ -200,7 +235,7 @@ extension ListViewController: UISearchResultsUpdating {
 }
 
 extension ListViewController: UISearchBarDelegate {
-    func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
+    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
         filterContentForSearchText(searchBar.text!, scope: selectedScope)
     }
 }
diff --git a/enzevalos_iphone/LogHandler.swift b/enzevalos_iphone/LogHandler.swift
index 191903affd4859fdf30a59dde227e84ea892dcf4..b6f5c720573fd5a8cb0186a82c3ef2c7b103e7e5 100644
--- a/enzevalos_iphone/LogHandler.swift
+++ b/enzevalos_iphone/LogHandler.swift
@@ -11,25 +11,25 @@ import UIKit
 
 class LogHandler {
     
-    private static var defaults = NSUserDefaults.init()
+    private static var defaults = UserDefaults.init()
     private(set) static var logging = false
-    private static var date = NSDate.init()
+    private static var date = Date.init()
     static var session : Int = 0
     
     static func newLog(){
         logging = true
-        session = defaults.integerForKey("Session")
+        session = defaults.integer(forKey: "Session")
         if session == 0{
             session = 1
         }
         else {
             session += 1
         }
-        defaults.setInteger(session, forKey: "Session")
-        defaults.setInteger(0, forKey: String(session)+"-index")
-        defaults.setObject("time,caller,interaction,point,comment"/*"time,caller,interaction,point,debugDescription,comment"*/, forKey: String(session)+"-0")
-        date = NSDate.init()
-        defaults.setObject(date.description, forKey: String(session)+"-date")
+        defaults.set(session, forKey: "Session")
+        defaults.set(0, forKey: String(session)+"-index")
+        defaults.set("time,caller,interaction,point,comment"/*"time,caller,interaction,point,debugDescription,comment"*/, forKey: String(session)+"-0")
+        date = Date.init()
+        defaults.set(date.description, forKey: String(session)+"-date")
         print("Logging Session: ",session)
         print(date.description)
     }
@@ -39,45 +39,45 @@ class LogHandler {
     }
     
     //TODO: escaping in comment and debugDescription
-    static func doLog(caller: String?, interaction: String, point: CGPoint, /*debugDescription: String,*/ comment : String){
+    static func doLog(_ caller: String?, interaction: String, point: CGPoint, /*debugDescription: String,*/ comment : String){
         var entry = ""
-        let now = NSDate.init()
+        let now = Date.init()
         //Zeit holen
-        entry.appendContentsOf(String(now.timeIntervalSinceDate(date)))
-        entry.appendContentsOf(",")
+        entry.append(String(now.timeIntervalSince(date)))
+        entry.append(",")
         //caller identifizieren
         if caller != nil{
-            entry.appendContentsOf(caller!)
+            entry.append(caller!)
         }
-        entry.appendContentsOf(",")
+        entry.append(",")
         //interaction bestimmen
-        entry.appendContentsOf(interaction)
-        entry.appendContentsOf(",")
+        entry.append(interaction)
+        entry.append(",")
         //Punkt anbinden
-        entry.appendContentsOf(String(point))
-        entry.appendContentsOf(",")
+        entry.append(String(describing: point))
+        entry.append(",")
         //debugDescription anhängen
         //entry.appendContentsOf(debugDescription)
         //entry.appendContentsOf(",")
         //text anbinden
-        entry.appendContentsOf(comment)
+        entry.append(comment)
         //in nsuserdefaults speichern
-        var index = defaults.integerForKey(String(session)+"-index")
+        var index = defaults.integer(forKey: String(session)+"-index")
         index += 1
-        defaults.setInteger(index, forKey: String(session)+"-index")
-        defaults.setObject(entry, forKey: String(session)+"-"+String(index))
+        defaults.set(index, forKey: String(session)+"-index")
+        defaults.set(entry, forKey: String(session)+"-"+String(index))
     }
     
     //methode zum auslesen eines logs
-    static func printLog(session : Int){
+    static func printLog(_ session : Int){
         print()
         print("--------------------LOG OUTPUT--------------------")
         print("LoggingSession ",session)
-        print(defaults.objectForKey(String(session)+"-date"))
+        print(defaults.object(forKey: String(session)+"-date"))
         print()
-        for i in 0 ..< defaults.integerForKey(String(session)+"-index")+1{
-            if let entry = defaults.objectForKey(String(session)+"-"+String(i)) {
-                    print(String(entry))
+        for i in 0 ..< defaults.integer(forKey: String(session)+"-index")+1{
+            if let entry = defaults.object(forKey: String(session)+"-"+String(i)) {
+                    print(String(describing: entry))
             }
             else {
                 print(",,,,")//print(",,,,,")
@@ -90,45 +90,45 @@ class LogHandler {
     }
     
     static func printLogs(){
-        for i in 1 ..< defaults.integerForKey("Session")+1 {
+        for i in 1 ..< defaults.integer(forKey: "Session")+1 {
             printLog(i)
         }
     }
     
-    static func getLog(session : Int) -> String{
-        var log = "\n--------------------LOG OUTPUT--------------------\nLoggingSession "+String(session)+"\n"+String(defaults.objectForKey(String(session)+"-date"))+"\n\n"
+    static func getLog(_ session : Int) -> String{
+        var log = "\n--------------------LOG OUTPUT--------------------\nLoggingSession "+String(session)+"\n"+String(describing: defaults.object(forKey: String(session)+"-date"))+"\n\n"
         
-        for  i in 0 ..< defaults.integerForKey(String(session)+"-index")+1{
-            if let entry = defaults.objectForKey(String(session)+"-"+String(i)) {
-                log.appendContentsOf(String(entry)+"\n")
+        for  i in 0 ..< defaults.integer(forKey: String(session)+"-index")+1{
+            if let entry = defaults.object(forKey: String(session)+"-"+String(i)) {
+                log.append(String(describing: entry)+"\n")
             }
             else {
-                log.appendContentsOf(",,,,\n")//log.appendContentsOf(",,,,,\n")
+                log.append(",,,,\n")//log.appendContentsOf(",,,,,\n")
             }
         }
-        log.appendContentsOf("\n--------------------------------------------------\n\n")
+        log.append("\n--------------------------------------------------\n\n")
         
         return log
     }
     
     static func getLogs() -> String {
         var logs = ""
-        for i in 1 ..< defaults.integerForKey("Session")+1 {
-            logs.appendContentsOf(getLog(i))
+        for i in 1 ..< defaults.integer(forKey: "Session")+1 {
+            logs.append(getLog(i))
         }
         return logs
     }
     
     //methode zum löschen bestimmter logs
-    static func deleteLog(session: Int){
+    static func deleteLog(_ session: Int){
         if logging{
             print("not deleting anything, active logging at the moment")
             return
         }
-        for i in 0 ..< defaults.integerForKey(String(session)+"-index")+1{
-            defaults.removeObjectForKey(String(session)+"-"+String(i))
+        for i in 0 ..< defaults.integer(forKey: String(session)+"-index")+1{
+            defaults.removeObject(forKey: String(session)+"-"+String(i))
         }
-        defaults.removeObjectForKey(String(session)+"-index")
+        defaults.removeObject(forKey: String(session)+"-index")
     }
     
     static func deleteLogs(){
@@ -136,9 +136,9 @@ class LogHandler {
             print("not deleting anything, active logging at the moment")
             return
         }
-        for i in 1 ..< defaults.integerForKey("Session")+1 {
+        for i in 1 ..< defaults.integer(forKey: "Session")+1 {
             deleteLog(i)
         }
-        defaults.setInteger(0, forKey: "Session")
+        defaults.set(0, forKey: "Session")
     }
 }
diff --git a/enzevalos_iphone/Mail+CoreDataProperties.swift b/enzevalos_iphone/Mail+CoreDataProperties.swift
index 4c462db01fe7e66e5c448446006d0a46eff6f8ae..70891d319011a43db53cbecbcb5d72c02621e396 100644
--- a/enzevalos_iphone/Mail+CoreDataProperties.swift
+++ b/enzevalos_iphone/Mail+CoreDataProperties.swift
@@ -12,33 +12,33 @@ import CoreData
 
 extension Mail {
 
-    @nonobjc public override class func fetchRequest() -> NSFetchRequest {
+    @nonobjc public override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
         return NSFetchRequest(entityName: "Mail");
     }
 
     @NSManaged public var body: String?
     @NSManaged public var visibleBody: String?
     @NSManaged public var decryptedBody: String?
-    @NSManaged public var date: NSDate
+    @NSManaged public var date: Date
     public var flag: MCOMessageFlag{
         set {
             if newValue != flag{
                 AppDelegate.getAppDelegate().mailHandler.addFlag(self.uid, flags: newValue)
-                self.willChangeValueForKey("flag")
+                self.willChangeValue(forKey: "flag")
                 self.setPrimitiveValue(newValue.rawValue, forKey: "flag")
-                self.didChangeValueForKey("flag")
+                self.didChangeValue(forKey: "flag")
                 
             }
             
         }
         get {
-            self.willAccessValueForKey("flag")
-            var value = MCOMessageFlag.None.rawValue
-            if let flagInt = self.primitiveValueForKey("flag"){
+            self.willAccessValue(forKey: "flag")
+            var value = MCOMessageFlag().rawValue
+            if let flagInt = self.primitiveValue(forKey: "flag"){
                 value = flagInt as! Int
             }
             let text = MCOMessageFlag(rawValue: value)
-            self.didAccessValueForKey("flag")
+            self.didAccessValue(forKey: "flag")
             return text
         }
 
@@ -51,14 +51,14 @@ extension Mail {
     @NSManaged public var subject: String?
     public var trouble: Bool{
         set {
-            self.willChangeValueForKey("trouble")
+            self.willChangeValue(forKey: "trouble")
             self.setPrimitiveValue(newValue, forKey: "trouble")
-            self.didChangeValueForKey("trouble")
+            self.didChangeValue(forKey: "trouble")
         }
         get {
-            self.willAccessValueForKey("trouble")
-            let text = self.primitiveValueForKey("trouble") as? Bool
-            self.didAccessValueForKey("trouble")
+            self.willAccessValue(forKey: "trouble")
+            let text = self.primitiveValue(forKey: "trouble") as? Bool
+            self.didAccessValue(forKey: "trouble")
             if(text == nil){
                 print("NIL!!!")
             }
@@ -69,14 +69,14 @@ extension Mail {
     public var uid: UInt64{
     
         set {
-            self.willChangeValueForKey("uid")
-            self.setPrimitiveValue(NSDecimalNumber.init(unsignedLongLong: newValue), forKey: "uid")
-            self.didChangeValueForKey("uid")
+            self.willChangeValue(forKey: "uid")
+            self.setPrimitiveValue(NSDecimalNumber.init(value: newValue as UInt64), forKey: "uid")
+            self.didChangeValue(forKey: "uid")
         }
         get {
-            self.willAccessValueForKey("uid")
-            let text = (self.primitiveValueForKey("uid") as? NSDecimalNumber)?.unsignedLongLongValue
-            self.didAccessValueForKey("uid")
+            self.willAccessValue(forKey: "uid")
+            let text = (self.primitiveValue(forKey: "uid") as? NSDecimalNumber)?.uint64Value
+            self.didAccessValue(forKey: "uid")
             return text!
         }
     }
@@ -91,16 +91,16 @@ extension Mail {
 extension Mail {
 
     @objc(addBccObject:)
-    @NSManaged public func addToBcc(value: Mail_Address)
+    @NSManaged public func addToBcc(_ value: Mail_Address)
 
     @objc(removeBccObject:)
-    @NSManaged public func removeFromBcc(value: Mail_Address)
+    @NSManaged public func removeFromBcc(_ value: Mail_Address)
 
     @objc(addBcc:)
-    @NSManaged public func addToBcc(values: NSSet)
+    @NSManaged public func addToBcc(_ values: NSSet)
 
     @objc(removeBcc:)
-    @NSManaged public func removeFromBcc(values: NSSet)
+    @NSManaged public func removeFromBcc(_ values: NSSet)
 
 }
 
@@ -108,16 +108,16 @@ extension Mail {
 extension Mail {
 
     @objc(addCcObject:)
-    @NSManaged public func addToCc(value: Mail_Address)
+    @NSManaged public func addToCc(_ value: Mail_Address)
 
     @objc(removeCcObject:)
-    @NSManaged public func removeFromCc(value: Mail_Address)
+    @NSManaged public func removeFromCc(_ value: Mail_Address)
 
     @objc(addCc:)
-    @NSManaged public func addToCc(values: NSSet)
+    @NSManaged public func addToCc(_ values: NSSet)
 
     @objc(removeCc:)
-    @NSManaged public func removeFromCc(values: NSSet)
+    @NSManaged public func removeFromCc(_ values: NSSet)
 
 }
 
@@ -125,15 +125,15 @@ extension Mail {
 extension Mail {
 
     @objc(addToObject:)
-    @NSManaged public func addToTo(value: Mail_Address)
+    @NSManaged public func addToTo(_ value: Mail_Address)
 
     @objc(removeToObject:)
-    @NSManaged public func removeFromTo(value: Mail_Address)
+    @NSManaged public func removeFromTo(_ value: Mail_Address)
 
     @objc(addTo:)
-    @NSManaged public func addToTo(values: NSSet)
+    @NSManaged public func addToTo(_ values: NSSet)
 
     @objc(removeTo:)
-    @NSManaged public func removeFromTo(values: NSSet)
+    @NSManaged public func removeFromTo(_ values: NSSet)
 
 }
diff --git a/enzevalos_iphone/MailAddress.swift b/enzevalos_iphone/MailAddress.swift
index cb3dc11dfe7b8a7c9d69dcd22364fb5766b6a97d..0f2f0a2c3451efbaffe5d429bb5503116f0d1cdd 100644
--- a/enzevalos_iphone/MailAddress.swift
+++ b/enzevalos_iphone/MailAddress.swift
@@ -11,7 +11,7 @@ import Contacts
 
 public protocol MailAddress { 
     var mailAddress:String{get}
-    var label: CNLabeledValue{get}
+    var label: CNLabeledValue<NSString>{get} //FIXME: ist der NSString hier wirklich richtig? (http://stackoverflow.com/questions/39648830/how-to-add-new-email-to-cnmutablecontact-in-swift-3)
     var prefEnc: Bool{get set}
     var hasKey: Bool{get}
 }
diff --git a/enzevalos_iphone/MailHandler.swift b/enzevalos_iphone/MailHandler.swift
index 24d74635a3194733e16c6c6a8224e323e8a50823..0f7b30059c775446b439c59b7a736f684dcb7fb8 100644
--- a/enzevalos_iphone/MailHandler.swift
+++ b/enzevalos_iphone/MailHandler.swift
@@ -27,6 +27,30 @@
 
 import Foundation
 import Contacts
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l < r
+  case (nil, _?):
+    return true
+  default:
+    return false
+  }
+}
+
+// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
+// Consider refactoring the code to use the non-optional operators.
+fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
+  switch (lhs, rhs) {
+  case let (l?, r?):
+    return l > r
+  default:
+    return rhs < lhs
+  }
+}
+
 
 
 let AUTOCRYPTHEADER = "Autocrypt"
@@ -51,7 +75,7 @@ class AutocryptContact {
 
 
     convenience init(header: MCOMessageHeader) {
-        let autocrypt = header.extraHeaderValueForName(AUTOCRYPTHEADER)
+        let autocrypt = header.extraHeaderValue(forName: AUTOCRYPTHEADER)
         var field: [String]
         var addr = ""
         var type = "p" // Default value since no one else uses autocrypt...
@@ -59,11 +83,11 @@ class AutocryptContact {
         var key = ""
 
         if(autocrypt != nil) {
-            let autocrypt_fields = autocrypt.componentsSeparatedByString(";")
-            for f in autocrypt_fields {
-                field = f.componentsSeparatedByString("=")
+            let autocrypt_fields = autocrypt?.components(separatedBy: ";")
+            for f in autocrypt_fields! {
+                field = f.components(separatedBy: "=")
                 if field.count > 1 {
-                    let flag = field[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
+                    let flag = field[0].trimmingCharacters(in: CharacterSet.whitespaces)
                     var value = field[1]
                     if field.count > 2 {
                         for i in 2...(field.count - 1) {
@@ -103,7 +127,7 @@ class AutocryptContact {
         return false
     }
 
-    func setPrefer_encryption(input: String) -> Bool {
+    func setPrefer_encryption(_ input: String) -> Bool {
         if input == "yes" || input == "YES" || input == "Yes" {
             prefer_encryption = true
             return true
@@ -124,12 +148,12 @@ class MailHandler {
 
     var delegate: MailHandlerDelegator?
 
-    private static let MAXMAILS: Int = 10
+    fileprivate static let MAXMAILS: Int = 10
 
 
 
-    private let concurrentMailServer = dispatch_queue_create(
-                                                             "com.enzevalos.mailserverQueue", DISPATCH_QUEUE_CONCURRENT)
+    fileprivate let concurrentMailServer = DispatchQueue(
+                                                             label: "com.enzevalos.mailserverQueue", attributes: DispatchQueue.Attributes.concurrent)
 
     var IMAPSes: MCOIMAPSession?
 
@@ -147,16 +171,16 @@ class MailHandler {
     //TODO: signatur hinzufügen
 
 
-    func add_autocrypt_header(builder: MCOMessageBuilder) {
-        let adr = UserManager.loadUserValue(Attribute.UserAddr) as! String
+    func add_autocrypt_header(_ builder: MCOMessageBuilder) {
+        let adr = UserManager.loadUserValue(Attribute.userAddr) as! String
         let pgpenc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP) as! PGPEncryption
         builder.header.setExtraHeaderValue(pgpenc.autocryptHeader(adr), forName: AUTOCRYPTHEADER)
     }
     
-    private func createHeader(builder: MCOMessageBuilder, toEntrys: [String], ccEntrys: [String], bccEntrys: [String], subject: String){
+    fileprivate func createHeader(_ builder: MCOMessageBuilder, toEntrys: [String], ccEntrys: [String], bccEntrys: [String], subject: String){
         
-        let username = UserManager.loadUserValue(Attribute.UserName) as! String
-        let useraddr = (UserManager.loadUserValue(Attribute.UserAddr) as! String)
+        let username = UserManager.loadUserValue(Attribute.userName) as! String
+        let useraddr = (UserManager.loadUserValue(Attribute.userAddr) as! String)
 
     
         var toReady: [MCOAddress] = []
@@ -186,10 +210,10 @@ class MailHandler {
     }
 
     //return if send successfully
-    func send(toEntrys: [String], ccEntrys: [String], bccEntrys: [String], subject: String, message: String, callback: (NSError?) -> Void) {
+    func send(_ toEntrys: [String], ccEntrys: [String], bccEntrys: [String], subject: String, message: String, callback: @escaping (NSError?) -> Void) {
         //http://stackoverflow.com/questions/31485359/sending-mailcore2-plain-emails-in-swift
 
-        let useraddr = (UserManager.loadUserValue(Attribute.UserAddr) as! String)
+        let useraddr = (UserManager.loadUserValue(Attribute.userAddr) as! String)
         let session = createSMTPSession()
         let builder = MCOMessageBuilder()
 
@@ -199,8 +223,8 @@ class MailHandler {
         // MailAddresses statt strings??
 
         var allRec: [String] = []
-        allRec.appendContentsOf(toEntrys)
-        allRec.appendContentsOf(ccEntrys)
+        allRec.append(contentsOf: toEntrys)
+        allRec.append(contentsOf: ccEntrys)
         // What about BCC??
 
         //TODO add support for different Encryptions here
@@ -210,7 +234,7 @@ class MailHandler {
         let userID = MCOAddress(displayName: useraddr, mailbox: useraddr)
 
         var encryption: Encryption
-        var sendData: NSData
+        var sendData: Data
         let orderedString = EnzevalosEncryptionHandler.sortMailaddressesByEncryption(allRec)
         var sendOperation: MCOSMTPSendOperation
 
@@ -220,12 +244,12 @@ class MailHandler {
             encryption = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)!
             if let encData = encryption.signAndEncrypt("\n"+message, mailaddresses: orderedString[EncryptionType.PGP]!) { //ohne "\n" wird der erste Teil der Nachricht, bis sich ein einzelnen \n in einer Zeile befindet nicht in die Nachricht getan
                 //sendData = encData
-                builder.textBody = String(data: encData, encoding: NSUTF8StringEncoding)
+                builder.textBody = String(data: encData, encoding: String.Encoding.utf8)
                 sendData = builder.data()
-                sendOperation = session.sendOperationWithData(sendData, from: userID, recipients: encPGP)
+                sendOperation = session.sendOperation(with: sendData, from: userID, recipients: encPGP)
                 //sendOperation = session.sendOperationWithData(builder.openPGPEncryptedMessageDataWithEncryptedData(sendData), from: userID, recipients: encPGP)
                 //TODO handle different callbacks
-                sendOperation.start(callback)
+                sendOperation.start(callback as! (Error?) -> Void)
                 builder.textBody = message
             }
                 else {
@@ -237,49 +261,49 @@ class MailHandler {
         if let unenc = ordered[EncryptionType.unknown] {
             builder.textBody = message
             sendData = builder.data()
-            sendOperation = session.sendOperationWithData(sendData, from: userID, recipients: unenc)
+            sendOperation = session.sendOperation(with: sendData, from: userID, recipients: unenc)
             //TODO handle different callbacks
-            sendOperation.start(callback)
+            sendOperation.start(callback as! (Error?) -> Void)
         }
     }
 
     func setupIMAPSession() {
         let imapsession = MCOIMAPSession()
-        imapsession.hostname = UserManager.loadUserValue(Attribute.IMAPHostname) as! String
-        imapsession.port = UInt32(UserManager.loadUserValue(Attribute.IMAPPort) as! Int)
-        imapsession.username = UserManager.loadUserValue(Attribute.UserAddr) as! String
-        imapsession.password = UserManager.loadUserValue(Attribute.UserPW) as! String
-        imapsession.authType = MCOAuthType(rawValue: UserManager.loadUserValue(Attribute.IMAPAuthType) as! Int) //MCOAuthType.SASLPlain
-        imapsession.connectionType = MCOConnectionType(rawValue: UserManager.loadUserValue(Attribute.IMAPConnectionType) as! Int)//MCOConnectionType.TLS
+        imapsession.hostname = UserManager.loadUserValue(Attribute.imapHostname) as! String
+        imapsession.port = UInt32(UserManager.loadUserValue(Attribute.imapPort) as! Int)
+        imapsession.username = UserManager.loadUserValue(Attribute.userAddr) as! String
+        imapsession.password = UserManager.loadUserValue(Attribute.userPW) as! String
+        imapsession.authType = MCOAuthType(rawValue: UserManager.loadUserValue(Attribute.imapAuthType) as! Int) //MCOAuthType.SASLPlain
+        imapsession.connectionType = MCOConnectionType(rawValue: UserManager.loadUserValue(Attribute.imapConnectionType) as! Int)//MCOConnectionType.TLS
         self.IMAPSes = imapsession
     }
     
-    private func createSMTPSession()-> MCOSMTPSession{
+    fileprivate func createSMTPSession()-> MCOSMTPSession{
         let session = MCOSMTPSession()
-        session.hostname = UserManager.loadUserValue(Attribute.SMTPHostname) as! String
-        session.port = UInt32(UserManager.loadUserValue(Attribute.SMTPPort) as! Int)
-        session.username = (UserManager.loadUserValue(Attribute.UserAddr) as! String)
-        session.password = UserManager.loadUserValue(Attribute.UserPW) as! String
-        session.authType = MCOAuthType(rawValue: UserManager.loadUserValue(Attribute.SMTPAuthType) as! Int)
-        session.connectionType = MCOConnectionType(rawValue: UserManager.loadUserValue(Attribute.SMTPConnectionType) as! Int)
+        session.hostname = UserManager.loadUserValue(Attribute.smtpHostname) as! String
+        session.port = UInt32(UserManager.loadUserValue(Attribute.smtpPort) as! Int)
+        session.username = (UserManager.loadUserValue(Attribute.userAddr) as! String)
+        session.password = UserManager.loadUserValue(Attribute.userPW) as! String
+        session.authType = MCOAuthType(rawValue: UserManager.loadUserValue(Attribute.smtpAuthType) as! Int)
+        session.connectionType = MCOConnectionType(rawValue: UserManager.loadUserValue(Attribute.smtpConnectionType) as! Int)
         return session
     }
 
 
 
-    func addFlag(uid: UInt64, flags: MCOMessageFlag, folder: String = "INBOX") {
-        let op = self.IMAPSession.storeFlagsOperationWithFolder(folder, uids: MCOIndexSet.init(index: uid), kind: MCOIMAPStoreFlagsRequestKind.Set, flags: flags)
-        op.start { error -> Void in
+    func addFlag(_ uid: UInt64, flags: MCOMessageFlag, folder: String = "INBOX") {
+        let op = self.IMAPSession.storeFlagsOperation(withFolder: folder, uids: MCOIndexSet.init(index: uid), kind: MCOIMAPStoreFlagsRequestKind.set, flags: flags)
+        op?.start { error -> Void in
             if let err = error {
                 print("Error while updating flags: \(err)")
             }
         }
     }
 
-    func removeFlag(uid: UInt64, flags: MCOMessageFlag, folder: String = "INBOX") {
-        let op = self.IMAPSession.storeFlagsOperationWithFolder(folder, uids: MCOIndexSet.init(index: uid), kind: MCOIMAPStoreFlagsRequestKind.Remove, flags: flags)
+    func removeFlag(_ uid: UInt64, flags: MCOMessageFlag, folder: String = "INBOX") {
+        let op = self.IMAPSession.storeFlagsOperation(withFolder: folder, uids: MCOIndexSet.init(index: uid), kind: MCOIMAPStoreFlagsRequestKind.remove, flags: flags)
 
-        op.start { error -> Void in
+        op?.start { error -> Void in
             if let err = error {
                 print("Error while updating flags: \(err)")
             } else {
@@ -289,32 +313,32 @@ class MailHandler {
     }
 
 
-    func receiveAll(folder: String = "INBOX", newMailCallback: (() -> ()), completionCallback: ((error: Bool) -> ())) {
+    func receiveAll(_ folder: String = "INBOX", newMailCallback: @escaping (() -> ()), completionCallback: @escaping ((_ error: Bool) -> ())) {
         let uids: MCOIndexSet
         uids = MCOIndexSet(range: MCORangeMake(DataHandler.handler.maxUID, UINT64_MAX))
         loadMessagesFromServer(uids, record: nil, newMailCallback: newMailCallback, completionCallback: completionCallback)
     }
 
-    func loadMoreMails(record: KeyRecord, folder: String = "INBOX", newMailCallback: (() -> ()), completionCallback: ((error: Bool) -> ())) {
+    func loadMoreMails(_ record: KeyRecord, folder: String = "INBOX", newMailCallback: @escaping (() -> ()), completionCallback: @escaping ((_ error: Bool) -> ())) {
         let addresses: [MailAddress]
         addresses = record.addresses
 
         for adr in addresses {
-            let searchExpr: MCOIMAPSearchExpression = MCOIMAPSearchExpression.searchFrom(adr.mailAddress)
-            let searchOperation: MCOIMAPSearchOperation = self.IMAPSession.searchExpressionOperationWithFolder(folder, expression: searchExpr)
+            let searchExpr: MCOIMAPSearchExpression = MCOIMAPSearchExpression.search(from: adr.mailAddress)
+            let searchOperation: MCOIMAPSearchOperation = self.IMAPSession.searchExpressionOperation(withFolder: folder, expression: searchExpr)
 
             searchOperation.start { (err, indices) -> Void in
                 guard err == nil else {
-                    completionCallback(error: true)
+                    completionCallback(true)
                     return
                 }
                 let ids = indices as MCOIndexSet?
                 if var setOfIndices = ids {
                     for mail in record.mails {
-                        setOfIndices.removeIndex(mail.uid)
+                        setOfIndices.remove(mail.uid)
                     }
                     if setOfIndices.count() == 0 {
-                        completionCallback(error: false)
+                        completionCallback(false)
                         return
                     }
                     print("Size first: \(setOfIndices.count())")
@@ -327,36 +351,36 @@ class MailHandler {
         }
     }
 
-    func loadMessagesFromServer(uids: MCOIndexSet, folder: String = "INBOX", record: KeyRecord?, newMailCallback: (() -> ()), completionCallback: ((error: Bool) -> ())) {
-        let requestKind = MCOIMAPMessagesRequestKind(rawValue: MCOIMAPMessagesRequestKind.Headers.rawValue | MCOIMAPMessagesRequestKind.Flags.rawValue)
-        let fetchOperation : MCOIMAPFetchMessagesOperation = self.IMAPSession.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)
+    func loadMessagesFromServer(_ uids: MCOIndexSet, folder: String = "INBOX", record: KeyRecord?, newMailCallback: @escaping (() -> ()), completionCallback: @escaping ((_ error: Bool) -> ())) {
+        let requestKind = MCOIMAPMessagesRequestKind(rawValue: MCOIMAPMessagesRequestKind.headers.rawValue | MCOIMAPMessagesRequestKind.flags.rawValue)
+        let fetchOperation : MCOIMAPFetchMessagesOperation = self.IMAPSession.fetchMessagesOperation(withFolder: folder, requestKind: requestKind, uids: uids)
         fetchOperation.extraHeaders = [AUTOCRYPTHEADER]
         
         fetchOperation.start { (err, msg, vanished) -> Void in
             guard err == nil else {
                 print("Error while fetching inbox: \(err)")
-                completionCallback(error: true)
+                completionCallback(true)
                 return
             }
             if let msgs = msg {
-                let dispatchGroup = dispatch_group_create()
+                let dispatchGroup = DispatchGroup()
                 for m in msgs {
                     let message: MCOIMAPMessage = m as! MCOIMAPMessage
-                    dispatch_group_enter(dispatchGroup)
+                    dispatchGroup.enter()
 
-                    let op = self.IMAPSession.fetchParsedMessageOperationWithFolder(folder, uid: message.uid)
-                    op.start { err, data in self.parseMail(err, parser: data, message: message, record: record, newMailCallback: newMailCallback)
-                        dispatch_group_leave(dispatchGroup)
+                    let op = self.IMAPSession.fetchParsedMessageOperation(withFolder: folder, uid: message.uid)
+                    op?.start { err, data in self.parseMail(err, parser: data, message: message, record: record, newMailCallback: newMailCallback)
+                        dispatchGroup.leave()
                     }
                 }
-                dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) {
+                dispatchGroup.notify(queue: DispatchQueue.main) {
                     self.IMAPSession.disconnectOperation().start({ _ in })
-                    completionCallback(error: false)
+                    completionCallback(false)
                 }
             }
         }
     }
-func parseMail(error: ErrorType?, parser: MCOMessageParser?, message: MCOIMAPMessage, record: KeyRecord?, newMailCallback: (() -> ())) {
+func parseMail(_ error: Error?, parser: MCOMessageParser?, message: MCOIMAPMessage, record: KeyRecord?, newMailCallback: (() -> ())) {
       guard error == nil else {
             print("Error while fetching mail: \(error)")
             return
@@ -364,24 +388,24 @@ func parseMail(error: ErrorType?, parser: MCOMessageParser?, message: MCOIMAPMes
         if let data = parser?.data() {
             let msgParser = MCOMessageParser(data: data)
 
-            let html: String = msgParser.plainTextRendering()
-            var lineArray = html.componentsSeparatedByString("\n")
+            let html: String = msgParser!.plainTextRendering()
+            var lineArray = html.components(separatedBy: "\n")
            
             lineArray.removeFirst(4)
-            var body = lineArray.joinWithSeparator("\n")
-            body = body.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
-            body.appendContentsOf("\n")
+            var body = lineArray.joined(separator: "\n")
+            body = body.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+            body.append("\n")
             var rec: [MCOAddress] = []
             var cc: [MCOAddress] = []
 
             let header = message.header
             var autocrypt: AutocryptContact? = nil
-            if let _ = header.extraHeaderValueForName(AUTOCRYPTHEADER){
-                autocrypt = AutocryptContact(header: header)
+            if let _ = header?.extraHeaderValue(forName: AUTOCRYPTHEADER){
+                autocrypt = AutocryptContact(header: header!)
                 print(autocrypt?.toString())
                 if(autocrypt?.type == EncryptionType.PGP && autocrypt?.key.characters.count > 0){
                     let pgp = ObjectivePGP.init()
-                    pgp.importPublicKeyFromHeader((autocrypt?.key)!, allowDuplicates: false)
+                    pgp.importPublicKey(fromHeader: (autocrypt?.key)!, allowDuplicates: false)
                     let enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
                     do {
                         let pgpKey = try pgp.keys[0].export()
@@ -393,12 +417,12 @@ func parseMail(error: ErrorType?, parser: MCOMessageParser?, message: MCOIMAPMes
                 }
                 
             }
-            if let to = header.to {
+            if let to = header?.to {
                 for r in to {
                     rec.append(r as! MCOAddress)
                 }
             }
-            if let c = header.cc {
+            if let c = header?.cc {
                 for r in c {
                     cc.append(r as! MCOAddress)
                 }
@@ -410,30 +434,30 @@ func parseMail(error: ErrorType?, parser: MCOMessageParser?, message: MCOIMAPMes
     }
 
 
-    private func cutIndexSet(inputSet: MCOIndexSet, maxMails: Int = MAXMAILS) -> MCOIndexSet {
+    fileprivate func cutIndexSet(_ inputSet: MCOIndexSet, maxMails: Int = MAXMAILS) -> MCOIndexSet {
         let max = UInt32(maxMails)
         if inputSet.count() <= max {
             return inputSet
         }
         let result = MCOIndexSet()
-        for x in inputSet.nsIndexSet().reverse() {
+        for x in inputSet.nsIndexSet().reversed() {
             if(result.count() < max) {
-                result.addIndex(UInt64(x))
+                result.add(UInt64(x))
             }
         }
         return result
     }
 
 
-    func findMaxUID(folder: String = "INBOX", callback: ((maxUID: UInt64) -> ())) {
+    func findMaxUID(_ folder: String = "INBOX", callback: @escaping ((_ maxUID: UInt64) -> ())) {
         //TODO: NSP!!!
         var maxUID: UInt64 = 0
-        let requestKind = MCOIMAPMessagesRequestKind(rawValue: MCOIMAPMessagesRequestKind.Headers.rawValue)
+        let requestKind = MCOIMAPMessagesRequestKind(rawValue: MCOIMAPMessagesRequestKind.headers.rawValue)
         let uids = MCOIndexSet(range: MCORangeMake(0, UINT64_MAX))
-        let dispatchGroup = dispatch_group_create()
-        dispatch_group_enter(dispatchGroup)
+        let dispatchGroup = DispatchGroup()
+        dispatchGroup.enter()
 
-        let fetchOperation: MCOIMAPFetchMessagesOperation = self.IMAPSession.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)
+        let fetchOperation: MCOIMAPFetchMessagesOperation = self.IMAPSession.fetchMessagesOperation(withFolder: folder, requestKind: requestKind, uids: uids)
         fetchOperation.start { (err, msg, vanished) -> Void in
             guard err == nil else {
                 print("Error while fetching inbox: \(err)")
@@ -448,127 +472,34 @@ func parseMail(error: ErrorType?, parser: MCOMessageParser?, message: MCOIMAPMes
                     }
                 }
             }
-            dispatch_group_leave(dispatchGroup)
+            dispatchGroup.leave()
         }
-        dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) {
-            callback(maxUID: maxUID)
+        dispatchGroup.notify(queue: DispatchQueue.main) {
+            callback(maxUID)
         }
     }
 
-    /*
-     Parameters:
-     ---------------
-     
-     Folder = ["INBOX"] (Default)
-     #mails = 200 (Default)
-     Look forspefic mail addreses (of Contacts) (optional) -> more folders?
-     Look for spefic threadID (optional) -> more folders?
-     Look for spefic date (optional) -> more folders
-     Look for unread messages (optional)
-     /
-    func lookForMailAddresses(mailaddresses: [String]?, startDate: NSDate?, endDate: NSDate?, folders: [String] = ["INBOX"], maxMails: Int = MAXMAILS, callback: ((mails: [Mail]) -> ()) ){
-        let qualityOfServiceClass = QOS_CLASS_BACKGROUND
-        let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
-        dispatch_async(backgroundQueue, {
-            
-        let dispatchGroup = dispatch_group_create()
-
-        if let mailadr = mailaddresses{
-            for adr in mailadr{
-                dispatch_group_enter(dispatchGroup)
-                self.lookForMailAddress(adr, startDate: startDate, endDate: endDate, folders: folders, dispatchGroup: dispatchGroup, callback: callback)
-            }
-        }
-        else{
-            dispatch_group_enter(dispatchGroup)
-            self.lookForDate(startDate: startDate, endDate: endDate, folders: folders, dispatchGroup: dispatchGroup, callback: callback)
-        }
-    }
-    
-    private func lookForDate(expr: MCOIMAPSearchExpression? = nil, startDate: NSDate?, endDate: NSDate?, folders: [String], dispatchGroup: dispatch_group_t,  callback: ((mails: [Mail]) -> ())){
-        if expr == nil && startDate == nil && endDate == nil{
-            //return nil
-        }
-        var ids: MCOIndexSet?
-        var searchExpr: MCOIMAPSearchExpression
-        
-        if expr != nil{
-            searchExpr = expr!
-        }
-        else {
-            searchExpr = MCOIMAPSearchExpression()
-        }
-        if startDate != nil {
-            let exprStartDate: MCOIMAPSearchExpression = MCOIMAPSearchExpression.searchSinceReceivedDate(startDate)
-            searchExpr = MCOIMAPSearchExpression.searchAnd(searchExpr, other: exprStartDate)
-        }
-        if endDate != nil {
-            let exprEndDate: MCOIMAPSearchExpression = MCOIMAPSearchExpression.searchBeforeDate(endDate)
-            searchExpr = MCOIMAPSearchExpression.searchAnd(searchExpr, other: exprEndDate)
-        }
-        let searchOperation: MCOIMAPSearchOperation = self.IMAPSession.searchExpressionOperationWithFolder(folders[0], expression: searchExpr)
-
-        searchOperation.start { (err, indices) -> Void  in
-            guard err == nil else {
-                return
-            }
-            ids = indices as MCOIndexSet?
-            //TODO Make thread safe!!!
-
-<<<<<<< HEAD
-            // Handle mails!
-            dispatch_group_leave(dispatchGroup)
- 
-        }
-        
-=======
-    func loadMoreMails(record: KeyRecord, newMailCallback: (() -> ()), completionCallback: ((error: Bool) -> ())) {
-        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
-            completionCallback(error: false)
-        })
->>>>>>> 3b095ad801e84b3f530f67c054a4adb8cdb465d7
-    }
-    
-    
-    private func lookForMailAddress(mailaddress: String, startDate: NSDate?, endDate: NSDate?, folders: [String], dispatchGroup: dispatch_group_t,  callback: ((mails: [Mail]) -> ())){
-        print(mailaddress)
-        let searchExpr: MCOIMAPSearchExpression = MCOIMAPSearchExpression.searchFrom(mailaddress)
-        lookForDate(searchExpr, startDate: startDate, endDate: endDate, folders: folders, dispatchGroup: dispatchGroup,  callback: callback)
-       
-    }
- */
-
-    func checkSMTP(completion: (NSError?) -> Void) {
-        let useraddr = (UserManager.loadUserValue(Attribute.UserAddr) as! String)
-        let username = UserManager.loadUserValue(Attribute.UserName) as! String
+    func checkSMTP(_ completion: (NSError?) -> Void) {
+        let useraddr = (UserManager.loadUserValue(Attribute.userAddr) as! String)
+        let username = UserManager.loadUserValue(Attribute.userName) as! String
         
         let session = MCOSMTPSession()
-        session.hostname = UserManager.loadUserValue(Attribute.SMTPHostname) as! String
-        session.port = UInt32(UserManager.loadUserValue(Attribute.SMTPPort) as! Int)
+        session.hostname = UserManager.loadUserValue(Attribute.smtpHostname) as! String
+        session.port = UInt32(UserManager.loadUserValue(Attribute.smtpPort) as! Int)
         session.username = username
-        session.password = UserManager.loadUserValue(Attribute.UserPW) as! String
-        session.authType = MCOAuthType.init(rawValue: UserManager.loadUserValue(Attribute.SMTPAuthType) as! Int)//MCOAuthType.SASLPlain
-        session.connectionType = MCOConnectionType.init(rawValue: UserManager.loadUserValue(Attribute.SMTPConnectionType) as! Int)//MCOConnectionType.StartTLS
+        session.password = UserManager.loadUserValue(Attribute.userPW) as! String
+        session.authType = MCOAuthType.init(rawValue: UserManager.loadUserValue(Attribute.smtpAuthType) as! Int)//MCOAuthType.SASLPlain
+        session.connectionType = MCOConnectionType.init(rawValue: UserManager.loadUserValue(Attribute.smtpConnectionType) as! Int)//MCOConnectionType.StartTLS
         
-        session.checkAccountOperationWithFrom(MCOAddress.init(mailbox: useraddr)).start(completion)
+        session.checkAccountOperationWith(from: MCOAddress.init(mailbox: useraddr)).start(completion)
         
     }
     
-    func checkIMAP(completion: (NSError?) -> Void) {
+    func checkIMAP(_ completion: @escaping (NSError?) -> Void) {
         self.setupIMAPSession()
         
-        /*let requestKind = MCOIMAPMessagesRequestKind(rawValue: MCOIMAPMessagesRequestKind.Headers.rawValue)
-        let uids = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))
-        
-        let fetchOperation: MCOIMAPFetchMessagesOperation = self.IMAPSession.fetchMessagesOperationWithFolder("INBOX", requestKind: requestKind, uids: uids)
-        fetchOperation.start { (err, msg, vanished) -> Void in
-            print("Hallo")
-            completion(err)
-        }
-        print("called")*/
-        
-        self.IMAPSession.checkAccountOperation().start(completion)
-        self.IMAPSession.connectOperation().start(completion)
+        self.IMAPSession.checkAccountOperation().start(completion as! (Error?) -> Void)
+        self.IMAPSession.connectOperation().start(completion as! (Error?) -> Void)
     }
     
     
diff --git a/enzevalos_iphone/MailHandlerDelegator.swift b/enzevalos_iphone/MailHandlerDelegator.swift
index b2ed204968adbf4a8e83c59aa9b51166699397be..a72c196b3532cc554240d26791dcbde539d32dc5 100644
--- a/enzevalos_iphone/MailHandlerDelegator.swift
+++ b/enzevalos_iphone/MailHandlerDelegator.swift
@@ -9,6 +9,6 @@
 import Foundation
 
 protocol MailHandlerDelegator {
-    func addNewMail(mail: Mail)
+    func addNewMail(_ mail: Mail)
     func getMailCompleted()
 }
diff --git a/enzevalos_iphone/Mail_Address+CoreDataClass.swift b/enzevalos_iphone/Mail_Address+CoreDataClass.swift
index 0de5ff3a64327afe4dcfcb073f37ceee34d265e6..872bf93e396dec0737c38563760e26dd6e39bb23 100644
--- a/enzevalos_iphone/Mail_Address+CoreDataClass.swift
+++ b/enzevalos_iphone/Mail_Address+CoreDataClass.swift
@@ -12,24 +12,24 @@ import CoreData
 import Contacts
 
 @objc(Mail_Address)
-public class Mail_Address: NSManagedObject, MailAddress {
+open class Mail_Address: NSManagedObject, MailAddress {
 
-    public var mailAddress: String {
+    open var mailAddress: String {
         return address
     }
 
-    public var label: CNLabeledValue {
+    open var label: CNLabeledValue<NSString> { //Wie in MailAddress; Ist der NSString hier richtig? (http://stackoverflow.com/questions/39648830/how-to-add-new-email-to-cnmutablecontact-in-swift-3)
         if let cnc = self.contact.cnContact {
             for adr in cnc.emailAddresses {
-                if adr.value as! String == address {
+                if adr.value as String == address {
                     return adr
                 }
             }
         }
-        return CNLabeledValue.init(label: CNLabelOther, value: address)
+        return CNLabeledValue.init(label: CNLabelOther, value: address as NSString)
     }
 
-    public var prefEnc: Bool {
+    open var prefEnc: Bool {
         get{
             return prefer_encryption
         }
@@ -39,7 +39,7 @@ public class Mail_Address: NSManagedObject, MailAddress {
     }
 
     //TODO think about it!
-    public var keyID: String? {
+    open var keyID: String? {
         get {
             if let encryption = EnzevalosEncryptionHandler.getEncryption(self.encryptionType) {
                 return encryption.getActualKeyID(self.address)
@@ -67,7 +67,7 @@ public class Mail_Address: NSManagedObject, MailAddress {
         }
     }
 
-    public var hasKey: Bool {
+    open var hasKey: Bool {
         if let encryption = EnzevalosEncryptionHandler.getEncryption(self.encryptionType) {
             return encryption.hasKey(self.mailAddress)
         }
diff --git a/enzevalos_iphone/Mail_Address+CoreDataProperties.swift b/enzevalos_iphone/Mail_Address+CoreDataProperties.swift
index 525b93f71e3cb988581d26500d4c60de9fa556ea..0bd743e93fcf1007dfb30661641faff05c3becaf 100644
--- a/enzevalos_iphone/Mail_Address+CoreDataProperties.swift
+++ b/enzevalos_iphone/Mail_Address+CoreDataProperties.swift
@@ -13,7 +13,7 @@ import CoreData
 
 extension Mail_Address {
 
-    @nonobjc public override class func fetchRequest() -> NSFetchRequest {
+    @nonobjc open override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
         return NSFetchRequest(entityName: "Mail_Address");
     }
 
@@ -24,16 +24,16 @@ extension Mail_Address {
     public var encryptionType: EncryptionType{
         set {
             let name = "encryptionType"
-            self.willChangeValueForKey(name)
+            self.willChangeValue(forKey: name)
             self.setPrimitiveValue(newValue.rawValue, forKey: name)
-            self.didChangeValueForKey(name)
+            self.didChangeValue(forKey: name)
         }
         get {
             
             let name = "encryptionType"
-            self.willAccessValueForKey(name)
-            let string = self.primitiveValueForKey(name) as! String?
-            self.didAccessValueForKey(name)
+            self.willAccessValue(forKey: name)
+            let string = self.primitiveValue(forKey: name) as! String?
+            self.didAccessValue(forKey: name)
             return EncryptionType.fromString(string)
          }
     }
@@ -51,16 +51,16 @@ extension Mail_Address {
 extension Mail_Address {
     
     @objc(addBccObject:)
-    @NSManaged public func addToBcc(value: Mail)
+    @NSManaged public func addToBcc(_ value: Mail)
     
     @objc(removeBccObject:)
-    @NSManaged public func removeFromBcc(value: Mail)
+    @NSManaged public func removeFromBcc(_ value: Mail)
     
     @objc(addBcc:)
-    @NSManaged public func addToBcc(values: NSSet)
+    @NSManaged public func addToBcc(_ values: NSSet)
     
     @objc(removeBcc:)
-    @NSManaged public func removeFromBcc(values: NSSet)
+    @NSManaged public func removeFromBcc(_ values: NSSet)
     
 }
 
@@ -68,16 +68,16 @@ extension Mail_Address {
 extension Mail_Address {
     
     @objc(addCcObject:)
-    @NSManaged public func addToCc(value: Mail)
+    @NSManaged public func addToCc(_ value: Mail)
     
     @objc(removeCcObject:)
-    @NSManaged public func removeFromCc(value: Mail)
+    @NSManaged public func removeFromCc(_ value: Mail)
     
     @objc(addCc:)
-    @NSManaged public func addToCc(values: NSSet)
+    @NSManaged public func addToCc(_ values: NSSet)
     
     @objc(removeCc:)
-    @NSManaged public func removeFromCc(values: NSSet)
+    @NSManaged public func removeFromCc(_ values: NSSet)
     
 }
 
@@ -85,15 +85,15 @@ extension Mail_Address {
 extension Mail_Address {
     
     @objc(addToObject:)
-    @NSManaged public func addToTo(value: Mail)
+    @NSManaged public func addToTo(_ value: Mail)
     
     @objc(removeToObject:)
-    @NSManaged public func removeFromTo(value: Mail)
+    @NSManaged public func removeFromTo(_ value: Mail)
     
     @objc(addTo:)
-    @NSManaged public func addToTo(values: NSSet)
+    @NSManaged public func addToTo(_ values: NSSet)
     
     @objc(removeTo:)
-    @NSManaged public func removeFromTo(values: NSSet)
+    @NSManaged public func removeFromTo(_ values: NSSet)
     
 }
diff --git a/enzevalos_iphone/NSDateCompare.swift b/enzevalos_iphone/NSDateCompare.swift
index 66072e3c5ebd27fa3637d0433c5a22a347a0ff75..cc299edabd031c7b1a56589ba8214486baa97e09 100644
--- a/enzevalos_iphone/NSDateCompare.swift
+++ b/enzevalos_iphone/NSDateCompare.swift
@@ -8,12 +8,12 @@
 
 import Foundation
 
-public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
-    return lhs === rhs || lhs.compare(rhs) == .OrderedSame
+/*public func ==(lhs: Date, rhs: Date) -> Bool {
+    return lhs === rhs || lhs.compare(rhs) == .orderedSame
 }
 
-public func <(lhs: NSDate, rhs: NSDate) -> Bool {
-    return lhs.compare(rhs) == .OrderedAscending
-}
+public func <(lhs: Date, rhs: Date) -> Bool {
+    return lhs.compare(rhs) == .orderedAscending
+}*/
 
-extension NSDate: Comparable { }
\ No newline at end of file
+//extension Date: Comparable { }
diff --git a/enzevalos_iphone/Onboarding.swift b/enzevalos_iphone/Onboarding.swift
index 83935f6cdeb452c210a4532d4502c23827a84e38..467feacca14c92cde2b0b440cd495dc7f1c66db6 100644
--- a/enzevalos_iphone/Onboarding.swift
+++ b/enzevalos_iphone/Onboarding.swift
@@ -41,7 +41,7 @@ class Onboarding {
     static var authenticationRows : [Int : String] = [MCOAuthType.SASLNone.rawValue : NSLocalizedString("None", comment: ""), MCOAuthType.SASLLogin.rawValue : "Login", MCOAuthType.SASLPlain.rawValue : NSLocalizedString("NormalPassword", comment: ""), MCOAuthType.SASLSRP.rawValue : "SRP", MCOAuthType.SASLCRAMMD5.rawValue : "CRAMMD5", MCOAuthType.SASLDIGESTMD5.rawValue : "DIGESTMD5", MCOAuthType.SASLNTLM.rawValue : "NTLM", MCOAuthType.SASLGSSAPI.rawValue : "GSSAPI", MCOAuthType.SASLKerberosV4.rawValue : "KerberosV4"]
     static var transportRows : [Int : String] = [MCOConnectionType.Clear.rawValue : NSLocalizedString("Plaintext", comment: ""), MCOConnectionType.StartTLS.rawValue : "StartTLS", MCOConnectionType.TLS.rawValue : "TLS"]
     
-    static func onboarding(callback: dispatch_block_t) -> UIViewController {
+    static func onboarding(_ callback: @escaping ()->()) -> UIViewController {
         
         //Background
         
@@ -55,16 +55,16 @@ class Onboarding {
         //
         // Clip context to a circle
         //
-        let path = CGPathCreateWithEllipseInRect(myBounds, nil);
-        CGContextAddPath(context!, path);
-        CGContextClip(context!);
+        let path = CGPath(ellipseIn: myBounds, transform: nil);
+        context!.addPath(path);
+        context!.clip();
         
         
         //
         // Fill background of context
         //
-        CGContextSetFillColorWithColor(context!, UIColor.init(red: 0.1, green: 1.0, blue: 0.3, alpha: 0.0).CGColor)
-        CGContextFillRect(context!, CGRectMake(0, 0, myBounds.size.width, myBounds.size.height));
+        context!.setFillColor(UIColor.init(red: 0.1, green: 1.0, blue: 0.3, alpha: 0.0).cgColor)
+        context!.fill(CGRect(x: 0, y: 0, width: myBounds.size.width, height: myBounds.size.height));
         
         let snapshot = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
@@ -72,26 +72,26 @@ class Onboarding {
         background = snapshot!
         
         //Content
-        let page1 = OnboardingContentViewController.contentWithTitle(NSLocalizedString("Hello", comment: "Welcome"), body: NSLocalizedString("InterestedInSecureMail", comment: "commendation to user for using secure mail"), image: nil, buttonText: nil, action: nil)
+        let page1 = OnboardingContentViewController.content(withTitle: NSLocalizedString("Hello", comment: "Welcome"), body: NSLocalizedString("InterestedInSecureMail", comment: "commendation to user for using secure mail"), image: nil, buttonText: nil, action: nil)
         mailaddress = UITextField.init()
         //text.textColor = UIColor.whiteColor()
         //text.tintColor = UIColor.whiteColor()
-        mailaddress.borderStyle = UITextBorderStyle.RoundedRect
-        mailaddress.keyboardType = UIKeyboardType.EmailAddress
-        mailaddress.autocorrectionType = UITextAutocorrectionType.No
+        mailaddress.borderStyle = UITextBorderStyle.roundedRect
+        mailaddress.keyboardType = UIKeyboardType.emailAddress
+        mailaddress.autocorrectionType = UITextAutocorrectionType.no
         mailaddress.frame = CGRect.init(x: 0, y: 0, width: 50, height: 30)
         mailaddress.placeholder = NSLocalizedString("Address", comment: "")
-        let page2 = OnboardingContentViewController.contentWithTitle(nil, body: NSLocalizedString("InsertMailAddress", comment: ""), videoURL: nil, inputView: mailaddress, buttonText: nil, actionBlock: nil)
+        let page2 = OnboardingContentViewController.content(withTitle: nil, body: NSLocalizedString("InsertMailAddress", comment: ""), videoURL: nil, inputView: mailaddress, buttonText: nil, actionBlock: nil)
         
         password = UITextField.init()
         //text.textColor = UIColor.whiteColor()
         //text.tintColor = UIColor.whiteColor()
-        password.borderStyle = UITextBorderStyle.RoundedRect
-        password.secureTextEntry = true
+        password.borderStyle = UITextBorderStyle.roundedRect
+        password.isSecureTextEntry = true
         password.frame = CGRect.init(x: 0, y: 0, width: 50, height: 30)
         password.placeholder = NSLocalizedString("Password", comment: "")
-        let page3 = OnboardingContentViewController.contentWithTitle(nil, body: NSLocalizedString("InsertPassword", comment: ""), videoURL: nil, inputView: password, buttonText: nil, actionBlock: nil)
-        let page4 = OnboardingContentViewController.contentWithTitle(NSLocalizedString("EverythingCorrect", comment: ""), body: nil, videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
+        let page3 = OnboardingContentViewController.content(withTitle: nil, body: NSLocalizedString("InsertPassword", comment: ""), videoURL: nil, inputView: password, buttonText: nil, actionBlock: nil)
+        let page4 = OnboardingContentViewController.content(withTitle: NSLocalizedString("EverythingCorrect", comment: ""), body: nil, videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
         
         
         return Onboard.OnboardingViewController(backgroundImage: background, contents: [page1, page2, page3, page4])
@@ -104,7 +104,7 @@ class Onboarding {
         let view = UIView.init()
         view.addSubview(activity)
         view.frame = activity.frame
-        let page1 = OnboardingContentViewController.contentWithTitle(NSLocalizedString("ConnectingToMailServer", comment: ""), body: nil, videoURL: nil, inputView: view, buttonText: nil, actionBlock: nil)
+        let page1 = OnboardingContentViewController.content(withTitle: NSLocalizedString("ConnectingToMailServer", comment: ""), body: nil, videoURL: nil, inputView: view, buttonText: nil, actionBlock: nil)
         
         return Onboard.OnboardingViewController(backgroundImage: background, contents: [page1])
     }
@@ -115,50 +115,50 @@ class Onboarding {
         let view = UIView.init()
         view.addSubview(activity)
         view.frame = activity.frame
-        let page1 = OnboardingContentViewController.contentWithTitle(NSLocalizedString("CreateAndManageKeys", comment: ""), body: nil, videoURL: nil, inputView: view, buttonText: nil, actionBlock: nil)
+        let page1 = OnboardingContentViewController.content(withTitle: NSLocalizedString("CreateAndManageKeys", comment: ""), body: nil, videoURL: nil, inputView: view, buttonText: nil, actionBlock: nil)
         
         return Onboard.OnboardingViewController(backgroundImage: background, contents: [page1])
     }
     
-    static func detailOnboarding(callback: dispatch_block_t) -> UIViewController {
+    static func detailOnboarding(_ callback: @escaping ()->()) -> UIViewController {
         
-        let start = OnboardingContentViewController.contentWithTitle(NSLocalizedString("WhatAShame", comment: ""), body: NSLocalizedString("CouldNotConnect", comment: ""), videoURL: nil, inputView: nil, buttonText: nil, actionBlock: nil)
+        let start = OnboardingContentViewController.content(withTitle: NSLocalizedString("WhatAShame", comment: ""), body: NSLocalizedString("CouldNotConnect", comment: ""), videoURL: nil, inputView: nil, buttonText: nil, actionBlock: nil)
         
         
-        let email = OnboardingContentViewController.contentWithTitle(nil, body: NSLocalizedString("InsertMailAddress", comment: ""), videoURL: nil, inputView: mailaddress, buttonText: nil, actionBlock: nil)
+        let email = OnboardingContentViewController.content(withTitle: nil, body: NSLocalizedString("InsertMailAddress", comment: ""), videoURL: nil, inputView: mailaddress, buttonText: nil, actionBlock: nil)
         
         username = UITextField.init()
         //text.textColor = UIColor.whiteColor()
         //text.tintColor = UIColor.whiteColor()
-        username.borderStyle = UITextBorderStyle.RoundedRect
-        username.keyboardType = UIKeyboardType.EmailAddress
-        username.autocorrectionType = UITextAutocorrectionType.No
+        username.borderStyle = UITextBorderStyle.roundedRect
+        username.keyboardType = UIKeyboardType.emailAddress
+        username.autocorrectionType = UITextAutocorrectionType.no
         username.frame = CGRect.init(x: 0, y: 0, width: 50, height: 30)
         username.placeholder = NSLocalizedString("Username", comment: "")
-        username.text = UserManager.loadUserValue(Attribute.UserName) as? String
+        username.text = UserManager.loadUserValue(Attribute.userName) as? String
         
-        let user = OnboardingContentViewController.contentWithTitle(nil, body: NSLocalizedString("InsertUsername", comment: ""), videoURL: nil, inputView: username, buttonText: nil, actionBlock: nil)
+        let user = OnboardingContentViewController.content(withTitle: nil, body: NSLocalizedString("InsertUsername", comment: ""), videoURL: nil, inputView: username, buttonText: nil, actionBlock: nil)
         
-        let passwd = OnboardingContentViewController.contentWithTitle(nil, body: NSLocalizedString("InsertPassword", comment: ""), videoURL: nil, inputView: password, buttonText: nil, actionBlock: nil)
+        let passwd = OnboardingContentViewController.content(withTitle: nil, body: NSLocalizedString("InsertPassword", comment: ""), videoURL: nil, inputView: password, buttonText: nil, actionBlock: nil)
         
-        imapServer.borderStyle = UITextBorderStyle.RoundedRect
+        imapServer.borderStyle = UITextBorderStyle.roundedRect
         imapServer.frame = CGRect.init(x: 0, y: 0, width: 50, height: 30)
-        imapServer.text = UserManager.loadUserValue(Attribute.IMAPHostname) as? String
+        imapServer.text = UserManager.loadUserValue(Attribute.imapHostname) as? String
         
         let imapLabel = UILabel.init()
         imapLabel.text = "IMAP-Port"
         
-        imapLabel.textColor = UIColor.whiteColor();
+        imapLabel.textColor = UIColor.white;
         imapLabel.font = font
         imapLabel.numberOfLines = 0;
-        imapLabel.textAlignment = NSTextAlignment.Center;
+        imapLabel.textAlignment = NSTextAlignment.center;
         imapLabel.frame = CGRect.init(x: 0, y: imapServer.frame.height+padding, width: 50, height: 30)
-        imapPort.borderStyle = UITextBorderStyle.RoundedRect
+        imapPort.borderStyle = UITextBorderStyle.roundedRect
         imapPort.text = "0"
-        if let port = UserManager.loadUserValue(Attribute.IMAPPort) {
+        if let port = UserManager.loadUserValue(Attribute.imapPort) {
             imapPort.text = "\(port as! Int)"
         }
-        imapPort.keyboardType = UIKeyboardType.NumberPad
+        imapPort.keyboardType = UIKeyboardType.numberPad
         imapPort.frame = CGRect.init(x: 0, y: imapServer.frame.height+padding+imapLabel.frame.height+padding, width: 50, height: 30)
         
         let imap = UIView.init(frame: CGRect.init(x:0, y:0, width: 50, height: imapServer.frame.height+padding+imapLabel.frame.height+padding+imapPort.frame.height))
@@ -166,7 +166,7 @@ class Onboarding {
         imap.addSubview(imapLabel)
         imap.addSubview(imapPort)
         
-        let imap1 = OnboardingContentViewController.contentWithTitle(nil, body: "IMAP-Server", videoURL: nil, inputView: imap, buttonText: nil, actionBlock: nil)
+        let imap1 = OnboardingContentViewController.content(withTitle: nil, body: "IMAP-Server", videoURL: nil, inputView: imap, buttonText: nil, actionBlock: nil)
         
         imapTransportEncryption = UIPickerView()
         imapTransDataDelegate = PickerDataDelegate.init(rows: Array(transportRows.values))
@@ -175,9 +175,9 @@ class Onboarding {
         imapTransportEncryption.frame = CGRect.init(x: 0, y: 0, width: 50, height: 100)
         imapTransportEncryption.reloadAllComponents()
         //imapAuthentication.backgroundColor = UIColor.whiteColor()
-        var row = UserManager.loadUserValue(Attribute.IMAPConnectionType) as! Int
+        var row = UserManager.loadUserValue(Attribute.imapConnectionType) as! Int
         imapTransDataDelegate.pickedValue = transportRows[row]!
-        row = imapTransDataDelegate.rows.indexOf(transportRows[row]!)!
+        row = imapTransDataDelegate.rows.index(of: transportRows[row]!)!
         //if Array(transportRows.keys).contains(row){
             imapTransportEncryption.selectRow(row, inComponent: 0, animated: false)
         //}
@@ -185,10 +185,10 @@ class Onboarding {
         let imapAuthLabel = UILabel.init()
         imapAuthLabel.text = "IMAP-"+NSLocalizedString("Authentification", comment: "")
         
-        imapAuthLabel.textColor = UIColor.whiteColor();
+        imapAuthLabel.textColor = UIColor.white;
         imapAuthLabel.font = font
         imapAuthLabel.numberOfLines = 0;
-        imapAuthLabel.textAlignment = NSTextAlignment.Center;
+        imapAuthLabel.textAlignment = NSTextAlignment.center;
         imapAuthLabel.frame = CGRect.init(x: 0, y: imapTransportEncryption.frame.height, width: 50, height: 30)
         
         imapAuthentication = UIPickerView()
@@ -198,11 +198,11 @@ class Onboarding {
         imapAuthentication.frame = CGRect.init(x: 0, y: imapTransportEncryption.frame.height+imapAuthLabel.frame.height, width: 50, height: 100)
         imapAuthentication.reloadAllComponents()
         imapAuthentication.reloadInputViews()
-        imapAuthentication.tintColor = UIColor.whiteColor()
+        imapAuthentication.tintColor = UIColor.white
         //imapAuthentication.backgroundColor = UIColor.whiteColor()
-        row = UserManager.loadUserValue(Attribute.IMAPAuthType) as! Int
+        row = UserManager.loadUserValue(Attribute.imapAuthType) as! Int
         imapAuthDataDelegate.pickedValue = authenticationRows[row]!
-        row = Array(authenticationRows.values).indexOf(authenticationRows[row]!)!
+        row = Array(authenticationRows.values).index(of: authenticationRows[row]!)!
         //if Array(authenticationRows.keys).contains(row){
             imapAuthentication.selectRow(row, inComponent: 0, animated: false)
         //}
@@ -211,29 +211,29 @@ class Onboarding {
         imapAuth.addSubview(imapTransportEncryption)
         imapAuth.addSubview(imapAuthLabel)
         imapAuth.addSubview(imapAuthentication)
-        let boolPointer = UnsafeMutablePointer<ObjCBool>.alloc(1)
+        let boolPointer = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
         boolPointer[0] = false
-        let imap2 = OnboardingContentViewController.contentWithTitle(nil, body: "IMAP-"+NSLocalizedString("Transportencryption", comment: ""), videoURL: nil, inputView: imapAuth, buttonText: nil, actionBlock: nil, withPadding: boolPointer)
+        let imap2 = OnboardingContentViewController.content(withTitle: nil, body: "IMAP-"+NSLocalizedString("Transportencryption", comment: ""), videoURL: nil, inputView: imapAuth, buttonText: nil, actionBlock: nil, withPadding: boolPointer)
         
         
-        smtpServer.borderStyle = UITextBorderStyle.RoundedRect
-        smtpServer.text = UserManager.loadUserValue(Attribute.SMTPHostname) as? String
+        smtpServer.borderStyle = UITextBorderStyle.roundedRect
+        smtpServer.text = UserManager.loadUserValue(Attribute.smtpHostname) as? String
         smtpServer.frame = CGRect.init(x: 0, y: 0, width: 50, height: 30)
         
         let smtpLabel = UILabel.init()
         smtpLabel.text = "SMTP-Port"
         
-        smtpLabel.textColor = UIColor.whiteColor();
+        smtpLabel.textColor = UIColor.white;
         smtpLabel.font = font
         smtpLabel.numberOfLines = 0;
-        smtpLabel.textAlignment = NSTextAlignment.Center;
+        smtpLabel.textAlignment = NSTextAlignment.center;
         smtpLabel.frame = CGRect.init(x: 0, y: smtpServer.frame.height+padding, width: 50, height: 30)
-        smtpPort.borderStyle = UITextBorderStyle.RoundedRect
+        smtpPort.borderStyle = UITextBorderStyle.roundedRect
         smtpPort.text = "0"
-        if let port = UserManager.loadUserValue(Attribute.SMTPPort) {
+        if let port = UserManager.loadUserValue(Attribute.smtpPort) {
             smtpPort.text = "\(port as! Int)"
         }
-        smtpPort.keyboardType = UIKeyboardType.NumberPad
+        smtpPort.keyboardType = UIKeyboardType.numberPad
         smtpPort.frame = CGRect.init(x: 0, y: smtpServer.frame.height+padding+smtpLabel.frame.height+padding, width: 50, height: 30)
         
         let smtp = UIView.init(frame: CGRect.init(x:0, y:0, width: 50, height: smtpServer.frame.height+padding+smtpLabel.frame.height+padding+smtpPort.frame.height))
@@ -241,7 +241,7 @@ class Onboarding {
         smtp.addSubview(smtpLabel)
         smtp.addSubview(smtpPort)
         
-        let smtp1 = OnboardingContentViewController.contentWithTitle(nil, body: "SMTP-Server", videoURL: nil, inputView: smtp, buttonText: nil, actionBlock: nil)
+        let smtp1 = OnboardingContentViewController.content(withTitle: nil, body: "SMTP-Server", videoURL: nil, inputView: smtp, buttonText: nil, actionBlock: nil)
         
         smtpTransportEncryption = UIPickerView()
         smtpTransDataDelegate = PickerDataDelegate.init(rows: Array(transportRows.values))
@@ -250,9 +250,9 @@ class Onboarding {
         smtpTransportEncryption.frame = CGRect.init(x: 0, y: 0, width: 50, height: 100)
         smtpTransportEncryption.reloadAllComponents()
         //smtpAuthentication.backgroundColor = UIColor.whiteColor()
-        row = UserManager.loadUserValue(Attribute.SMTPConnectionType) as! Int
+        row = UserManager.loadUserValue(Attribute.smtpConnectionType) as! Int
         smtpTransDataDelegate.pickedValue = transportRows[row]!
-        row = smtpTransDataDelegate.rows.indexOf(transportRows[row]!)!
+        row = smtpTransDataDelegate.rows.index(of: transportRows[row]!)!
         //if Array(transportRows.keys).contains(row){
         smtpTransportEncryption.selectRow(row, inComponent: 0, animated: false)
         //}
@@ -260,10 +260,10 @@ class Onboarding {
         let smtpAuthLabel = UILabel.init()
         smtpAuthLabel.text = "SMTP-"+NSLocalizedString("Authentification", comment: "")
         
-        smtpAuthLabel.textColor = UIColor.whiteColor();
+        smtpAuthLabel.textColor = UIColor.white;
         smtpAuthLabel.font = font
         smtpAuthLabel.numberOfLines = 0;
-        smtpAuthLabel.textAlignment = NSTextAlignment.Center;
+        smtpAuthLabel.textAlignment = NSTextAlignment.center;
         smtpAuthLabel.frame = CGRect.init(x: 0, y: smtpTransportEncryption.frame.height, width: 50, height: 30)
         
         smtpAuthentication = UIPickerView()
@@ -273,11 +273,11 @@ class Onboarding {
         smtpAuthentication.frame = CGRect.init(x: 0, y: smtpTransportEncryption.frame.height+smtpAuthLabel.frame.height, width: 50, height: 100)
         smtpAuthentication.reloadAllComponents()
         smtpAuthentication.reloadInputViews()
-        smtpAuthentication.tintColor = UIColor.whiteColor()
+        smtpAuthentication.tintColor = UIColor.white
         //smtpAuthentication.backgroundColor = UIColor.whiteColor()
-        row = UserManager.loadUserValue(Attribute.SMTPAuthType) as! Int
+        row = UserManager.loadUserValue(Attribute.smtpAuthType) as! Int
         smtpAuthDataDelegate.pickedValue = authenticationRows[row]!
-        row = Array(authenticationRows.values).indexOf(authenticationRows[row]!)!
+        row = Array(authenticationRows.values).index(of: authenticationRows[row]!)!
         //if Array(authenticationRows.keys).contains(row){
         smtpAuthentication.selectRow(row, inComponent: 0, animated: false)
         //}
@@ -287,30 +287,30 @@ class Onboarding {
         smtpAuth.addSubview(smtpAuthLabel)
         smtpAuth.addSubview(smtpAuthentication)
         boolPointer[0] = false
-        let smtp2 = OnboardingContentViewController.contentWithTitle(nil, body: "SMTP-"+NSLocalizedString("Transportencryption", comment: ""), videoURL: nil, inputView: smtpAuth, buttonText: nil, actionBlock: nil, withPadding: boolPointer)
+        let smtp2 = OnboardingContentViewController.content(withTitle: nil, body: "SMTP-"+NSLocalizedString("Transportencryption", comment: ""), videoURL: nil, inputView: smtpAuth, buttonText: nil, actionBlock: nil, withPadding: boolPointer)
 
         
-        let last = OnboardingContentViewController.contentWithTitle(NSLocalizedString("EverythingCorrect", comment: ""), body: nil, videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
+        let last = OnboardingContentViewController.content(withTitle: NSLocalizedString("EverythingCorrect", comment: ""), body: nil, videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
         
         return Onboard.OnboardingViewController(backgroundImage: background, contents: [start, email, user, passwd, imap1, imap2, smtp1, smtp2, last])
     }
     
-    static func contactView(callback: () -> ()) -> UIViewController {
+    static func contactView(_ callback: @escaping () -> ()) -> UIViewController {
         let activity = UIActivityIndicatorView.init()
         activity.startAnimating()
         let view = UIView.init()
         view.addSubview(activity)
         view.frame = activity.frame
-        let page1 = OnboardingContentViewController.contentWithTitle(NSLocalizedString("AccessContacts", comment: ""), body: NSLocalizedString("AccessContactsDescription", comment: "Description, why we need access"), videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
+        let page1 = OnboardingContentViewController.content(withTitle: NSLocalizedString("AccessContacts", comment: ""), body: NSLocalizedString("AccessContactsDescription", comment: "Description, why we need access"), videoURL: nil, inputView: nil, buttonText: NSLocalizedString("next", comment: ""), actionBlock: callback)
         
         return Onboard.OnboardingViewController(backgroundImage: background, contents: [page1])
     }
     
-    static func checkContact(callback : (Bool) -> ()){
+    static func checkContact(_ callback : (Bool) -> ()){
         AppDelegate.getAppDelegate().requestForAccess(callback)
     }
     
-    static func checkConfig(fail: () -> (), work: () -> ()) -> Bool {
+    static func checkConfig(_ fail: @escaping () -> (), work: @escaping () -> ()) -> Bool {
         smtpCheckDone = false
         imapCheckDone = false
         manualSet = true
@@ -328,7 +328,7 @@ class Onboarding {
         return true
     }
     
-    static func imapCompletion(error: NSError?) {
+    static func imapCompletion(_ error: NSError?) {
         imapCheckDone = true
         imapCheck = error == nil
         if imapCheck {
@@ -338,7 +338,7 @@ class Onboarding {
         fail()
     }
     
-    static func smtpCompletion(error: NSError?){
+    static func smtpCompletion(_ error: NSError?){
         smtpCheckDone = true
         smtpCheck = error == nil
         if smtpCheck {
@@ -350,46 +350,46 @@ class Onboarding {
     
     static func setGuessValues() {
         
-        if let mailAddress = mailaddress.text where !manualSet && mailAddress != "" && mailAddress.containsString("@") {
-            let guessedUserName = mailAddress.componentsSeparatedByString("@")[0]
-            let provider = mailAddress.componentsSeparatedByString("@")[1]
-            UserManager.storeUserValue(mailAddress, attribute: Attribute.UserAddr)//Attribute.attributeValues[Attribute.UserAddr] = addr
-            UserManager.storeUserValue(guessedUserName, attribute: Attribute.UserName)
+        if let mailAddress = mailaddress.text, !manualSet && mailAddress != "" && mailAddress.contains("@") {
+            let guessedUserName = mailAddress.components(separatedBy: "@")[0]
+            let provider = mailAddress.components(separatedBy: "@")[1]
+            UserManager.storeUserValue(mailAddress, attribute: Attribute.userAddr)//Attribute.attributeValues[Attribute.UserAddr] = addr
+            UserManager.storeUserValue(guessedUserName, attribute: Attribute.userName)
             if provider == Provider.FU.rawValue {
                 Providers.setValues(Provider.FU)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.Accountname)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.UserName)
+                UserManager.storeUserValue("jakobsbode", attribute: Attribute.accountname)
+                UserManager.storeUserValue("jakobsbode", attribute: Attribute.userName)
             }
             if provider == Provider.ZEDAT.rawValue {
                 Providers.setValues(Provider.ZEDAT)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.Accountname)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.UserName)
+                UserManager.storeUserValue("jakobsbode", attribute: Attribute.accountname)
+                UserManager.storeUserValue("jakobsbode", attribute: Attribute.userName)
             }
             if provider == Provider.ENZEVALOS.rawValue {
                 Providers.setValues(Provider.ENZEVALOS)
-                UserManager.storeUserValue(guessedUserName, attribute: Attribute.Accountname)
-                UserManager.storeUserValue(guessedUserName, attribute: Attribute.UserName)
+                UserManager.storeUserValue(guessedUserName, attribute: Attribute.accountname)
+                UserManager.storeUserValue(guessedUserName, attribute: Attribute.userName)
             }
             if provider == Provider.WEB.rawValue {
                 Providers.setValues(Provider.WEB)
             }
         }
-        if let pw = password.text where pw != "" {
-            UserManager.storeUserValue(pw, attribute: Attribute.UserPW)
+        if let pw = password.text, pw != "" {
+            UserManager.storeUserValue(pw, attribute: Attribute.userPW)
         }
         if manualSet {
-            UserManager.storeUserValue(imapServer.text, attribute: Attribute.IMAPHostname)
-            UserManager.storeUserValue(Int(imapPort.text!), attribute: Attribute.IMAPPort)
-            UserManager.storeUserValue(smtpServer.text, attribute: Attribute.SMTPHostname)
-            UserManager.storeUserValue(Int(smtpPort.text!), attribute: Attribute.SMTPPort)
-            UserManager.storeUserValue(mailaddress.text, attribute: Attribute.UserAddr)
-            UserManager.storeUserValue(password.text!, attribute: Attribute.UserPW)
-            UserManager.storeUserValue(username.text!, attribute: Attribute.UserName)
-            UserManager.storeUserValue(username.text!, attribute: Attribute.Accountname)
-            UserManager.storeUserValue(keyForValue(transportRows, value: imapTransDataDelegate.pickedValue)[0], attribute: Attribute.IMAPConnectionType)
-            UserManager.storeUserValue(keyForValue(authenticationRows, value: imapAuthDataDelegate.pickedValue)[0], attribute: Attribute.IMAPAuthType)
-            UserManager.storeUserValue(keyForValue(transportRows, value: smtpTransDataDelegate.pickedValue)[0], attribute: Attribute.SMTPConnectionType)
-            UserManager.storeUserValue(keyForValue(authenticationRows, value: smtpAuthDataDelegate.pickedValue)[0], attribute: Attribute.SMTPAuthType)
+            UserManager.storeUserValue(imapServer.text, attribute: Attribute.imapHostname)
+            UserManager.storeUserValue(Int(imapPort.text!), attribute: Attribute.imapPort)
+            UserManager.storeUserValue(smtpServer.text, attribute: Attribute.smtpHostname)
+            UserManager.storeUserValue(Int(smtpPort.text!), attribute: Attribute.smtpPort)
+            UserManager.storeUserValue(mailaddress.text, attribute: Attribute.userAddr)
+            UserManager.storeUserValue(password.text!, attribute: Attribute.userPW)
+            UserManager.storeUserValue(username.text!, attribute: Attribute.userName)
+            UserManager.storeUserValue(username.text!, attribute: Attribute.accountname)
+            UserManager.storeUserValue(keyForValue(transportRows, value: imapTransDataDelegate.pickedValue)[0], attribute: Attribute.imapConnectionType)
+            UserManager.storeUserValue(keyForValue(authenticationRows, value: imapAuthDataDelegate.pickedValue)[0], attribute: Attribute.imapAuthType)
+            UserManager.storeUserValue(keyForValue(transportRows, value: smtpTransDataDelegate.pickedValue)[0], attribute: Attribute.smtpConnectionType)
+            UserManager.storeUserValue(keyForValue(authenticationRows, value: smtpAuthDataDelegate.pickedValue)[0], attribute: Attribute.smtpAuthType)
         }
         
     }
@@ -405,12 +405,12 @@ class Onboarding {
             //---------------------------------------
             //Import private Key BEGIN
             
-            var path = NSBundle.mainBundle().pathForResource("alice2005-private", ofType: "gpg")        //<---- Schlüsseldatei
-            if UserManager.loadUserValue(Attribute.UserAddr)!.containsString("@") && UserManager.loadUserValue(Attribute.UserAddr)!.componentsSeparatedByString("@")[1] == Provider.ENZEVALOS.rawValue {
-                path = NSBundle.mainBundle().pathForResource("quizer1-private", ofType: "asc")
+            var path = Bundle.main.path(forResource: "alice2005-private", ofType: "gpg")        //<---- Schlüsseldatei
+            if UserManager.loadUserValue(Attribute.userAddr)!.contains("@") && UserManager.loadUserValue(Attribute.userAddr)!.components(separatedBy: "@")[1] == Provider.ENZEVALOS.rawValue {
+                path = Bundle.main.path(forResource: "quizer1-private", ofType: "asc")
             }
             var pgp = ObjectivePGP.init()
-            pgp.importKeysFromFile(path!, allowDuplicates: false)
+            pgp.importKeys(fromFile: path!, allowDuplicates: false)
             var enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
             do {
                 let data = try pgp.keys[0].export()
@@ -423,9 +423,9 @@ class Onboarding {
             //---------------------------------------
             //Import public Key BEGIN
             
-            path = NSBundle.mainBundle().pathForResource("JakobBode", ofType: "asc")               //<---- Schlüsseldatei
+            path = Bundle.main.path(forResource: "JakobBode", ofType: "asc")               //<---- Schlüsseldatei
             pgp = ObjectivePGP.init()
-            pgp.importKeysFromFile(path!, allowDuplicates: false)
+            pgp.importKeys(fromFile: path!, allowDuplicates: false)
             enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
             do {
                 let data = try pgp.keys[0].export()
@@ -438,9 +438,9 @@ class Onboarding {
             //---------------------------------------
             //Import public Key BEGIN
             
-            path = NSBundle.mainBundle().pathForResource("alice2005-public", ofType: "gpg")               //<---- Schlüsseldatei
+            path = Bundle.main.path(forResource: "alice2005-public", ofType: "gpg")               //<---- Schlüsseldatei
             pgp = ObjectivePGP.init()
-            pgp.importKeysFromFile(path!, allowDuplicates: false)
+            pgp.importKeys(fromFile: path!, allowDuplicates: false)
             enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
             do {
                 let data = try pgp.keys[0].export()
@@ -453,9 +453,9 @@ class Onboarding {
             //---------------------------------------
             //Import public Key BEGIN
             
-            path = NSBundle.mainBundle().pathForResource("quizer1-public", ofType: "asc")               //<---- Schlüsseldatei
+            path = Bundle.main.path(forResource: "quizer1-public", ofType: "asc")               //<---- Schlüsseldatei
             pgp = ObjectivePGP.init()
-            pgp.importKeysFromFile(path!, allowDuplicates: false)
+            pgp.importKeys(fromFile: path!, allowDuplicates: false)
             enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
             do {
                 let data = try pgp.keys[0].export()
@@ -467,17 +467,18 @@ class Onboarding {
             //---------------------------------------
     }
     
-    static func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
+    static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
         var i = 0
-        return anyGenerator {
-            let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
-            return next.hashValue == i++ ? next : nil
+        return AnyIterator {
+            let next = withUnsafePointer(to: &i) { UnsafeRawPointer($0).load(as: T.self) }
+            i = i + 1
+            return next.hashValue == (i-1) ? next : nil
         }
     }
     
     
     //Inspired by http://stackoverflow.com/questions/32692450/swift-dictionary-get-key-for-values
-    static func keyForValue(dict : [Int : String], value : String) -> [Int]{
+    static func keyForValue(_ dict : [Int : String], value : String) -> [Int]{
         let keys = dict.filter {
             return $0.1 == value
             }.map {
@@ -496,11 +497,11 @@ class PickerDataDelegate : NSObject, UIPickerViewDataSource {
         self.rows = rows
     }
     
-    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
+    func numberOfComponents(in pickerView: UIPickerView) -> Int {
         return 1
     }
     
-    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
+    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
         return rows.count
     }
     
@@ -509,21 +510,21 @@ class PickerDataDelegate : NSObject, UIPickerViewDataSource {
 }
 extension PickerDataDelegate : UIPickerViewDelegate {
     
-    func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
+    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
         return 50
     }
     
-    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
+    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
         return rows[row]
     }
     
-    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
+    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
         let label = UILabel(frame: CGRect.init(x: 0, y: 0, width: 0/*pickerView.frame.width*/, height: 30))
         label.text = rows[row]
-        label.textAlignment = NSTextAlignment.Center
-        label.font = Onboarding.font?.fontWithSize((Onboarding.font?.pointSize)!-CGFloat(5))
+        label.textAlignment = NSTextAlignment.center
+        label.font = Onboarding.font?.withSize((Onboarding.font?.pointSize)!-CGFloat(5))
         //label.backgroundColor = UIColor.greenColor()
-        label.textColor = UIColor.whiteColor()
+        label.textColor = UIColor.white
         return label
     }
     
@@ -535,7 +536,7 @@ extension PickerDataDelegate : UIPickerViewDelegate {
     }*/
     
     
-    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
+    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
         pickedValue = rows[row]
     }
 }
diff --git a/enzevalos_iphone/OnboardingViewCells.swift b/enzevalos_iphone/OnboardingViewCells.swift
index b083908fd646186ca3a81d0f6232c4ed1259202a..6d38ce4a9d1598631ab4c2aa3db3c34ac28c48ee 100644
--- a/enzevalos_iphone/OnboardingViewCells.swift
+++ b/enzevalos_iphone/OnboardingViewCells.swift
@@ -8,7 +8,7 @@
 
 import UIKit
 
-public class SwitchCell : UITableViewCell {
+open class SwitchCell : UITableViewCell {
     @IBOutlet weak var label: UILabel!
     @IBOutlet weak var switcher: UISwitch!
 }
diff --git a/enzevalos_iphone/OnboardingViewController.swift b/enzevalos_iphone/OnboardingViewController.swift
index f18d7de6fd9ebdc3d5900bf9e7c21462245a9d0f..52d8024eab76547124ec6a383c1ba6f41a4398a0 100644
--- a/enzevalos_iphone/OnboardingViewController.swift
+++ b/enzevalos_iphone/OnboardingViewController.swift
@@ -33,24 +33,24 @@ class OnboardingViewController : UIViewController {
         EnzevalosEncryptionHandler.getEncryption(.PGP)?.printAllKeyIDs()
     }
     
-    @IBAction func privateKey(sender: AnyObject, forEvent event: UIEvent) {
+    @IBAction func privateKey(_ sender: AnyObject, forEvent event: UIEvent) {
         pKey = !pKey
     }
-    @IBAction func jakobKey(sender: AnyObject, forEvent event: UIEvent) {
+    @IBAction func jakobKey(_ sender: AnyObject, forEvent event: UIEvent) {
         jKey = !jKey
     }
-    @IBAction func aliceKey(sender: AnyObject, forEvent event: UIEvent) {
+    @IBAction func aliceKey(_ sender: AnyObject, forEvent event: UIEvent) {
         aKey = !aKey
     }
-    @IBAction func quizer1Key(sender: AnyObject, forEvent event: UIEvent) {
+    @IBAction func quizer1Key(_ sender: AnyObject, forEvent event: UIEvent) {
         q1Key = !q1Key
     }
     
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
         if segue.identifier == "onboarding" {
             var mAddr = ""
             var mPw = ""
-            if let addr = mailaddress?.text where addr != "" {
+            if let addr = mailaddress?.text, addr != "" {
                 //if addr.componentsSeparatedByString("@")[1] != "web.de" {
                 // naechste view
                 //}
@@ -59,7 +59,7 @@ class OnboardingViewController : UIViewController {
                  UserManager.storeUserValue(guessedUserName, attribute: Attribute.UserName)*/
                 mAddr = addr
             }
-            if let pw = password?.text where pw != "" {
+            if let pw = password?.text, pw != "" {
                 //UserManager.storeUserValue(pw, attribute: Attribute.UserPW)//Attribute.attributeValues[Attribute.UserPW] = pw
                 mPw = pw
             }
@@ -75,12 +75,12 @@ class OnboardingViewController : UIViewController {
                 //---------------------------------------
                 //Import private Key BEGIN
                 
-                 var path = NSBundle.mainBundle().pathForResource("alice2005-private", ofType: "gpg")        //<---- Schlüsseldatei
-                 if mAddr.containsString("@") && mAddr.componentsSeparatedByString("@")[1] == Provider.ENZEVALOS.rawValue {
-                        path = NSBundle.mainBundle().pathForResource("quizer1-private", ofType: "asc")
+                 var path = Bundle.main.path(forResource: "alice2005-private", ofType: "gpg")        //<---- Schlüsseldatei
+                 if mAddr.contains("@") && mAddr.components(separatedBy: "@")[1] == Provider.ENZEVALOS.rawValue {
+                        path = Bundle.main.path(forResource: "quizer1-private", ofType: "asc")
                  }
                 let pgp = ObjectivePGP.init()
-                 pgp.importKeysFromFile(path!, allowDuplicates: false)
+                 pgp.importKeys(fromFile: path!, allowDuplicates: false)
                  let enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
                  do {
                  let data = try pgp.keys[0].export()
@@ -95,9 +95,9 @@ class OnboardingViewController : UIViewController {
                 //---------------------------------------
                 //Import public Key BEGIN
                 
-                 let path = NSBundle.mainBundle().pathForResource("JakobBode", ofType: "asc")               //<---- Schlüsseldatei
+                 let path = Bundle.main.path(forResource: "JakobBode", ofType: "asc")               //<---- Schlüsseldatei
                  let pgp = ObjectivePGP.init()
-                 pgp.importKeysFromFile(path!, allowDuplicates: false)
+                 pgp.importKeys(fromFile: path!, allowDuplicates: false)
                  let enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
                  do {
                  let data = try pgp.keys[0].export()
@@ -112,9 +112,9 @@ class OnboardingViewController : UIViewController {
                 //---------------------------------------
                 //Import public Key BEGIN
                 
-                 let path = NSBundle.mainBundle().pathForResource("alice2005-public", ofType: "gpg")               //<---- Schlüsseldatei
+                 let path = Bundle.main.path(forResource: "alice2005-public", ofType: "gpg")               //<---- Schlüsseldatei
                  let pgp = ObjectivePGP.init()
-                 pgp.importKeysFromFile(path!, allowDuplicates: false)
+                 pgp.importKeys(fromFile: path!, allowDuplicates: false)
                  let enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
                  do {
                  let data = try pgp.keys[0].export()
@@ -129,9 +129,9 @@ class OnboardingViewController : UIViewController {
                 //---------------------------------------
                 //Import public Key BEGIN
                 
-                let path = NSBundle.mainBundle().pathForResource("quizer1-public", ofType: "asc")               //<---- Schlüsseldatei
+                let path = Bundle.main.path(forResource: "quizer1-public", ofType: "asc")               //<---- Schlüsseldatei
                 let pgp = ObjectivePGP.init()
-                pgp.importKeysFromFile(path!, allowDuplicates: false)
+                pgp.importKeys(fromFile: path!, allowDuplicates: false)
                 let enc = EnzevalosEncryptionHandler.getEncryption(EncryptionType.PGP)
                 do {
                     let data = try pgp.keys[0].export()
@@ -142,42 +142,43 @@ class OnboardingViewController : UIViewController {
                 //Import public key END
                 //---------------------------------------
             }
-            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "launchedBefore")
+            UserDefaults.standard.set(true, forKey: "launchedBefore")
         }
     }
     
-    func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
+    func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
         var i = 0
-        return anyGenerator {
-            let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
-            return next.hashValue == i++ ? next : nil
+        return AnyIterator {
+            let next = withUnsafePointer(to: &i) { UnsafeRawPointer($0).load(as: T.self) }
+            i += 1
+            return next.hashValue == i-1 ? next : nil
         }
     }
     
-    func setGuessValues(mailAddress: String, pw: String) {
+    func setGuessValues(_ mailAddress: String, pw: String) {
         if mailAddress != "" {
-            let guessedUserName = mailAddress.componentsSeparatedByString("@")[0]
-            let provider = mailAddress.componentsSeparatedByString("@")[1]
-            UserManager.storeUserValue(mailAddress, attribute: Attribute.UserAddr)//Attribute.attributeValues[Attribute.UserAddr] = addr
-            UserManager.storeUserValue(guessedUserName, attribute: Attribute.UserName)
+            let guessedUserName = mailAddress.components(separatedBy: "@")[0]
+            let provider = mailAddress.components(separatedBy: "@")[1]
+            UserManager.storeUserValue(mailAddress as AnyObject?, attribute: Attribute.userAddr)//Attribute.attributeValues[Attribute.UserAddr] = addr
+            UserManager.storeUserValue(guessedUserName as AnyObject?, attribute: Attribute.userName)
             if provider == Provider.FU.rawValue {
                 Providers.setValues(Provider.FU)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.Accountname)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.UserName)
+                UserManager.storeUserValue("jakobsbode" as AnyObject?, attribute: Attribute.accountname)
+                UserManager.storeUserValue("jakobsbode" as AnyObject?, attribute: Attribute.userName)
             }
             if provider == Provider.ZEDAT.rawValue {
                 Providers.setValues(Provider.ZEDAT)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.Accountname)
-                UserManager.storeUserValue("jakobsbode", attribute: Attribute.UserName)
+                UserManager.storeUserValue("jakobsbode" as AnyObject?, attribute: Attribute.accountname)
+                UserManager.storeUserValue("jakobsbode" as AnyObject?, attribute: Attribute.userName)
             }
             if provider == Provider.ENZEVALOS.rawValue {
                 Providers.setValues(Provider.ENZEVALOS)
-                UserManager.storeUserValue(guessedUserName, attribute: Attribute.Accountname)
-                UserManager.storeUserValue(guessedUserName, attribute: Attribute.UserName)
+                UserManager.storeUserValue(guessedUserName as AnyObject?, attribute: Attribute.accountname)
+                UserManager.storeUserValue(guessedUserName as AnyObject?, attribute: Attribute.userName)
             }
         }
         if pw != "" {
-            UserManager.storeUserValue(pw, attribute: Attribute.UserPW)
+            UserManager.storeUserValue(pw as AnyObject?, attribute: Attribute.userPW)
         }
         smtpCheckDone = false
         imapCheckDone = false
@@ -189,14 +190,14 @@ class OnboardingViewController : UIViewController {
         print("checks ", imapCheck, smtpCheck)
     }
     
-    private func SMTPCompletion(error: NSError?) {
+    private func SMTPCompletion(_ error: NSError?) {
         if error == nil {
             smtpCheck = true
         }
         smtpCheckDone = true
     }
     
-    private func IMAPCompletion(error: NSError?) {
+    private func IMAPCompletion(_ error: NSError?) {
         if error == nil {
             imapCheck = true
         }
@@ -211,7 +212,7 @@ extension OnboardingViewController : UITableViewDelegate {
 
 extension OnboardingViewController : UITableViewDataSource {
     
-    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         if section == 0 {
             return 2
         }
@@ -221,29 +222,29 @@ extension OnboardingViewController : UITableViewDataSource {
         return 0
     }
     
-    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
+    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         if section == 0 {
             return "Credentials"
         }
         return "Keys"
     }
     
-    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
+    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         if indexPath.section == 0 {
             if indexPath.row == 0 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("InputCell") as! InputCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "InputCell") as! InputCell
                 cell.label.text = "Mailaddress"
                 cell.textfield.placeholder = "address"
-                cell.textfield.keyboardType = UIKeyboardType.EmailAddress
-                cell.textfield.autocorrectionType = UITextAutocorrectionType.No
+                cell.textfield.keyboardType = UIKeyboardType.emailAddress
+                cell.textfield.autocorrectionType = UITextAutocorrectionType.no
                 self.mailaddress = cell.textfield
                 return cell
             }
             if indexPath.row == 1 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("InputCell") as! InputCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "InputCell") as! InputCell
                 cell.label.text = "Password"
                 cell.textfield.placeholder = "password"
-                cell.textfield.secureTextEntry = true
+                cell.textfield.isSecureTextEntry = true
                 self.password = cell.textfield
                 return cell
                 
@@ -251,35 +252,35 @@ extension OnboardingViewController : UITableViewDataSource {
         }
         if indexPath.section == 1 {
             if indexPath.row == 0 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell") as! SwitchCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell") as! SwitchCell
                 cell.label.text = "import private key"
-                cell.switcher.addTarget(self, action: #selector(privateKey), forControlEvents: .ValueChanged)
+                cell.switcher.addTarget(self, action: #selector(privateKey), for: .valueChanged)
                 return cell
             }
             if indexPath.row == 1 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell") as! SwitchCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell") as! SwitchCell
                 cell.label.text = "import jakob's pub-key"
-                cell.switcher.addTarget(self, action: #selector(jakobKey), forControlEvents: .ValueChanged)
+                cell.switcher.addTarget(self, action: #selector(jakobKey), for: .valueChanged)
                 return cell
             }
             if indexPath.row == 2 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell") as! SwitchCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell") as! SwitchCell
                 cell.label.text = "import alice's pub-key"
-                cell.switcher.addTarget(self, action: #selector(aliceKey), forControlEvents: .ValueChanged)
+                cell.switcher.addTarget(self, action: #selector(aliceKey), for: .valueChanged)
                 return cell
             }
             if indexPath.row == 3 {
-                let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell") as! SwitchCell
+                let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell") as! SwitchCell
                 cell.label.text = "import quizer1's pub-key"
-                cell.switcher.addTarget(self, action: #selector(quizer1Key), forControlEvents: .ValueChanged)
+                cell.switcher.addTarget(self, action: #selector(quizer1Key), for: .valueChanged)
                 return cell
             }
         }
-        let cell = tableView.dequeueReusableCellWithIdentifier("AliceKeyCell")!
+        let cell = tableView.dequeueReusableCell(withIdentifier: "AliceKeyCell")!
         return cell
     }
     
-    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+    func numberOfSections(in tableView: UITableView) -> Int {
         return 2
     }
 }
diff --git a/enzevalos_iphone/PGPEncryption.swift b/enzevalos_iphone/PGPEncryption.swift
index 0e9ada4224bd3cbb062e24872c30fcd5dd009982..b26dd336a96404eddddf9be1665731eaaca319df 100644
--- a/enzevalos_iphone/PGPEncryption.swift
+++ b/enzevalos_iphone/PGPEncryption.swift
@@ -28,7 +28,7 @@ class PGPEncryption : Encryption {
         return keyManager
     }
     
-    func isUsed(mail: Mail) -> Bool {
+    func isUsed(_ mail: Mail) -> Bool {
         if let plain = mail.body {
             return isUsed(plain, key: nil)
         }
@@ -36,15 +36,15 @@ class PGPEncryption : Encryption {
     }
     
     //key is unused
-    func isUsed(text: String, key: KeyWrapper?) -> Bool {
-        if let usedForSignature = self.isUsedForSignature(text, key: key) where usedForSignature {
+    func isUsed(_ text: String, key: KeyWrapper?) -> Bool {
+        if let usedForSignature = self.isUsedForSignature(text, key: key), usedForSignature {
             return true
         }
         return self.isUsedForEncryption(text, key: key)!
     }
     
     //check whether this encryption is used in this mail for encryption. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForEncryption(mail: Mail) -> Bool? {
+    func isUsedForEncryption(_ mail: Mail) -> Bool? {
         if let plain = mail.body {
             return isUsedForEncryption(plain, key: nil)
         }
@@ -53,12 +53,12 @@ class PGPEncryption : Encryption {
     
     //check whether this encryption is used in this text for encryption. the key is not known to be used. nil is returned, if there is no answer to be made at the moment.
     //key unused
-    func isUsedForEncryption(text: String, key: KeyWrapper?) -> Bool?{
+    func isUsedForEncryption(_ text: String, key: KeyWrapper?) -> Bool?{
         return text.hasPrefix("-----BEGIN PGP MESSAGE-----") && (text.hasSuffix("-----END PGP MESSAGE-----\n") || text.hasSuffix("-----END PGP MESSAGE-----"))
     }
     
     //check whether this encryption is used in this mail for signing. nil is returned, if there is no answer to be made at the moment.
-    func isUsedForSignature(mail: Mail) -> Bool?{
+    func isUsedForSignature(_ mail: Mail) -> Bool?{
         //TODO api-check
         //baut auf der Annahme auf, dass der signierte Teil nach dem entschlüsseln noch vorhanden ist.
         if let plain = mail.decryptedBody {
@@ -72,7 +72,7 @@ class PGPEncryption : Encryption {
     
     //check whether this encryption is used in this text for signing. nil is returned, if there is no answer to be made at the moment.
     //key unused
-    func isUsedForSignature(text: String, key: KeyWrapper?) -> Bool? {
+    func isUsedForSignature(_ text: String, key: KeyWrapper?) -> Bool? {
         if !isUsedForEncryption(text, key: nil)! {
             return text.hasPrefix("-----BEGIN PGP SIGNED MESSAGE-----") && (text.hasSuffix("-----END PGP SIGNATURE-----\n") || text.hasSuffix("-----END PGP SIGNATURE-----"))
         }
@@ -81,22 +81,22 @@ class PGPEncryption : Encryption {
     
     //TODO
     //decrypt the mails body. the decryted body will be saved in the mail object.
-    func decrypt(mail: Mail)-> String?{
+    func decrypt(_ mail: Mail)-> String?{
         if self.isUsed(mail) {
-            let bodyData = mail.body!.dataUsingEncoding(NSUTF8StringEncoding)!
+            let bodyData = mail.body!.data(using: String.Encoding.utf8)!
             var data = try? keyManager.pgp.decryptData(bodyData, passphrase: nil)
             if data == nil {
                 self.keyManager.useAllPrivateKeys()
                 //TODO add oldKeyUsed attribute in Mail object
-                data = try? keyManager.pgp.decryptData(mail.body!.dataUsingEncoding(NSUTF8StringEncoding)!, passphrase: nil)
+                data = try? keyManager.pgp.decryptData(mail.body!.data(using: String.Encoding.utf8)!, passphrase: nil)
                 self.keyManager.useOnlyActualPrivateKey()
                 if data != nil {
                     mail.decryptedWithOldPrivateKey = true
                 }
             }
             if let unwrappedData = data {
-                mail.decryptedBody = String(data: unwrappedData, encoding: NSUTF8StringEncoding)
-                return String(data: unwrappedData, encoding: NSUTF8StringEncoding)
+                mail.decryptedBody = String(data: unwrappedData, encoding: String.Encoding.utf8)
+                return String(data: unwrappedData, encoding: String.Encoding.utf8)
             }
         }
         /*if self.isUsed(mail) {
@@ -122,16 +122,16 @@ class PGPEncryption : Encryption {
         return nil
     }
     
-    func decryptAndSignatureCheck(mail: Mail) {
+    func decryptAndSignatureCheck(_ mail: Mail) {
         if self.isUsed(mail) {
-            let bodyData = mail.body!.dataUsingEncoding(NSUTF8StringEncoding)!
-            var data: NSData?
-            var error = NSErrorPointer.init()
+            let bodyData = mail.body!.data(using: String.Encoding.utf8)!
+            var data: Data?
+            var error: NSErrorPointer = NSErrorPointer.none
             var temp = keyManager.pgp.decryptDataFirstPart(bodyData, passphrase: nil, integrityProtected: nil, error: error)
             var maybeUsedKeys: [String] = []
-            var signed = UnsafeMutablePointer<ObjCBool>.alloc(1)
+            var signed = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
             signed[0] = false
-            var valid = UnsafeMutablePointer<ObjCBool>.alloc(1)
+            var valid = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
             valid[0] = false
             print(temp.incompleteKeyID,"  ",temp.onePassSignaturePacket)
                 data = temp.plaintextData
@@ -148,21 +148,27 @@ class PGPEncryption : Encryption {
                 mail.trouble = true
             }
                 if let unwrappedData = data {
-                    mail.decryptedBody = String(data: unwrappedData, encoding: NSUTF8StringEncoding)
-                    if let allKeyIDs = self.keyManager.getKeyIDsForMailAddress(mail.from.address), theirKeyID = temp.incompleteKeyID {
+                    mail.decryptedBody = String(data: unwrappedData, encoding: String.Encoding.utf8)
+                    if let allKeyIDs = self.keyManager.getKeyIDsForMailAddress(mail.from.address), let theirKeyID = temp.incompleteKeyID {
                         maybeUsedKeys = self.getLibaryKeyIDOverlap(theirKeyID, ourKeyIDs: allKeyIDs)
                     }
                     for maybeUsedKey in maybeUsedKeys {
                         if let key = self.keyManager.getKey(maybeUsedKey) {
-                            let done : ObjCBool = (self.keyManager.pgp.decryptDataSecondPart(temp, verifyWithPublicKey: key.key, signed: signed, valid: valid, error: error)[0])
+                            //FIXME
+                            let done : ObjCBool
+                            do {
+                                try done = (self.keyManager.pgp.decryptDataSecondPart(temp, verifyWithPublicKey: key.key, signed: signed, valid: valid)[0])
+                            } catch err {
+                                <#statements#>
+                            }
 
-                            if !done {
+                            if !done.boolValue {
                                 mail.isSigned = false
                                 mail.isCorrectlySigned = false
                                 break
                             }
-                            mail.isSigned = signed.memory.boolValue
-                            mail.isCorrectlySigned = valid.memory.boolValue
+                            mail.isSigned = signed.pointee.boolValue
+                            mail.isCorrectlySigned = valid.pointee.boolValue
                             if mail.isSigned && mail.isCorrectlySigned {
                                 mail.keyID = key.keyID
                                 break
@@ -179,7 +185,7 @@ class PGPEncryption : Encryption {
     }
     
     //decrypt the text with the given key and return it.
-    func decrypt(text: String, keyID: String) -> String?{
+    func decrypt(_ text: String, keyID: String) -> String?{
         if let privKeys = keyManager.getAllPrivateKeyIDs() {
             if !privKeys.contains(keyID) {
                 return nil
@@ -188,8 +194,8 @@ class PGPEncryption : Encryption {
         if let key = keyManager.getKey(keyID) {
             let pgp = ObjectivePGP.init()
             pgp.keys.append(key.key)
-            if let decr = try? pgp.decryptData(text.dataUsingEncoding(NSUTF8StringEncoding)!, passphrase: nil) {
-                return String(data: decr, encoding: NSUTF8StringEncoding)
+            if let decr = try? pgp.decryptData(text.data(using: String.Encoding.utf8)!, passphrase: nil) {
+                return String(data: decr, encoding: String.Encoding.utf8)
             }
         }
         return nil
@@ -197,25 +203,25 @@ class PGPEncryption : Encryption {
     
     //TODO
     //check whether the mail is correctly signed with this encryption. nil is returned, if there is no answer to be made at the moment.
-    func isCorrectlySigned(mail: Mail) -> Bool?{
+    func isCorrectlySigned(_ mail: Mail) -> Bool?{
         return false
     }
     
     //TODO
     //check whether the text is correctly signed with this encryption.
-    func isCorrectlySigned(text: String, key: KeyWrapper) -> Bool?{
+    func isCorrectlySigned(_ text: String, key: KeyWrapper) -> Bool?{
         return false
     }
     
     //TODO
     //encrypt mail for contact
-    func encrypt(mail: Mail){
+    func encrypt(_ mail: Mail){
         
     }
     
     //encrypt text with key
-    func encrypt(text: String, keyIDs: [String]) -> NSData? {
-        var encData : NSData? = nil
+    func encrypt(_ text: String, keyIDs: [String]) -> Data? {
+        var encData : Data? = nil
         var keys : [PGPKey] = []
         for id in keyIDs {
             if let key = keyManager.getKey(id) {
@@ -226,7 +232,7 @@ class PGPEncryption : Encryption {
                 return nil
             }
         }
-        if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
+        if let data = text.data(using: String.Encoding.utf8) {
             encData = try? keyManager.pgp.encryptData(data, usingPublicKeys: keys, armored: true)
         }
         else {
@@ -235,7 +241,7 @@ class PGPEncryption : Encryption {
         return encData
     }
     
-    func encrypt(text: String, mailaddresses: [String]) -> NSData? {
+    func encrypt(_ text: String, mailaddresses: [String]) -> Data? {
         var keyIDs : [String] = []
         for addr in mailaddresses {
             if let ids = keyManager.getKeyIDsForMailAddress(addr) {
@@ -258,24 +264,24 @@ class PGPEncryption : Encryption {
     
     //TODO
     //sign mail
-    func sign(mail: Mail){
+    func sign(_ mail: Mail){
         
     }
     
     //TODO
     //sign text
-    func sign(text: String, key: KeyWrapper) -> String{
+    func sign(_ text: String, key: KeyWrapper) -> String{
         return ""
     }
     
     //TODO
     //sign and encrypt mail for contact
-    func signAndEncrypt(mail: Mail, forContact: KeyRecord){
+    func signAndEncrypt(_ mail: Mail, forContact: KeyRecord){
         
     }
     
-    func signAndEncrypt(text: String, keyIDs: [String]) -> NSData? {
-        var encData : NSData? = nil
+    func signAndEncrypt(_ text: String, keyIDs: [String]) -> Data? {
+        var encData : Data? = nil
         var keys : [PGPKey] = []
         for id in keyIDs {
             if let key = keyManager.getKey(id) {
@@ -286,7 +292,7 @@ class PGPEncryption : Encryption {
                 return nil
             }
         }
-        if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
+        if let data = text.data(using: String.Encoding.utf8) {
             if let myKeyID = keyManager.getPrivateKeyID() {
                 if let myKey = keyManager.getKey(myKeyID) {
                     encData = try? keyManager.pgp.encryptData(data, usingPublicKeys: keys, signWithSecretKey: myKey.key, passphrase: "", armored: true)
@@ -305,7 +311,7 @@ class PGPEncryption : Encryption {
         return encData
     }
     
-    func signAndEncrypt(text: String, mailaddresses: [String]) -> NSData? {
+    func signAndEncrypt(_ text: String, mailaddresses: [String]) -> Data? {
         var keyIDs : [String] = []
         for addr in mailaddresses {
             if let ids = keyManager.getKeyIDsForMailAddress(addr) {
@@ -327,7 +333,7 @@ class PGPEncryption : Encryption {
     }
     
     //chooses first key in data. others will be ignored
-    func addKey(keyData: NSData, forMailAddress: String?) -> String? {
+    func addKey(_ keyData: Data, forMailAddress: String?) -> String? {
         var addrs : [String] = []
         if let addr = forMailAddress {
             addrs = [addr]
@@ -336,13 +342,13 @@ class PGPEncryption : Encryption {
     }
     
     //chooses first key in data. others will be ignored
-    func addKey(keyData: NSData, forMailAddresses: [String]?) -> String?{
+    func addKey(_ keyData: Data, forMailAddresses: [String]?) -> String?{
         return self.addKey(keyData, forMailAddresses: forMailAddresses, discoveryMailUID: nil)
     }
     
     //chooses first key in data. others will be ignored
-    func addKey(keyData: NSData, forMailAddresses: [String]?, discoveryMailUID: UInt64?) -> String? {
-        if let tmpKey = self.keyManager.pgp.keysFromData(keyData) {
+    func addKey(_ keyData: Data, forMailAddresses: [String]?, discoveryMailUID: UInt64?) -> String? {
+        if let tmpKey = self.keyManager.pgp.keys(from: keyData) {
             var addrs : [String] = []
             if let addr = forMailAddresses {
                 addrs = addr
@@ -354,7 +360,7 @@ class PGPEncryption : Encryption {
     }
     
     //chooses first key in data. others will be ignored
-    func addKey(keyData: NSData, discoveryMail: Mail?) -> String? {
+    func addKey(_ keyData: Data, discoveryMail: Mail?) -> String? {
         var discoveryMailUID: UInt64? = nil
         var forMailAddresses: [String]? = nil
         if let mail = discoveryMail {
@@ -382,16 +388,16 @@ class PGPEncryption : Encryption {
         return
     }*/
     
-    private func getMaxIndex(fingerprint: String) -> Int64 {
+    fileprivate func getMaxIndex(_ fingerprint: String) -> Int64 {
         var index : Int64 = 0
         if let indexData = encryptionHandler.getPersistentData(fingerprint+"-index", encryptionType: self.encryptionType){
-            indexData.getBytes(&index, length: sizeof(Int64))
+            (indexData as NSData).getBytes(&index, length: sizeof(Int64))
         }
         
         return index
     }
     
-    func hasKey(enzContact: EnzevalosContact) -> Bool {
+    func hasKey(_ enzContact: EnzevalosContact) -> Bool {
         if let addrs = enzContact.addresses {
             if let mailaddrs : [Mail_Address] = (addrs.allObjects as? [Mail_Address]) {
                 for mail in mailaddrs {
@@ -404,7 +410,7 @@ class PGPEncryption : Encryption {
         return false
     }
     
-    func hasKey(mailaddress: String) -> Bool {
+    func hasKey(_ mailaddress: String) -> Bool {
         if let ids = keyManager.getKeyIDsForMailAddress(mailaddress) {
             return ids != []
         }
@@ -412,20 +418,20 @@ class PGPEncryption : Encryption {
     }
     
     //TODO
-    func getKeyIDs(enzContact: EnzevalosContact) -> [String]? {
+    func getKeyIDs(_ enzContact: EnzevalosContact) -> [String]? {
         return nil
     }
     
-    func getKeyIDs(mailaddress: String) -> [String]?{
+    func getKeyIDs(_ mailaddress: String) -> [String]?{
         return keyManager.getKeyIDsForMailAddress(mailaddress)
     }
     
-    func getActualKeyID(mailaddress: String) -> String? {
+    func getActualKeyID(_ mailaddress: String) -> String? {
         return self.keyManager.getActualKeyIDForMailaddress(mailaddress)
     }
     
     
-    func getKey(keyID: String) -> KeyWrapper? {
+    func getKey(_ keyID: String) -> KeyWrapper? {
         return self.keyManager.getKey(keyID)
     }
     
@@ -434,11 +440,11 @@ class PGPEncryption : Encryption {
         
     }*/
     
-    func removeKey(keyID: String){
+    func removeKey(_ keyID: String){
         self.keyManager.removeKey(keyID)
     }
     
-    func removeKey(key: KeyWrapper) {
+    func removeKey(_ key: KeyWrapper) {
         self.removeKey(key.keyID)
     }
     
@@ -451,36 +457,36 @@ class PGPEncryption : Encryption {
         keyManager.printAllKeyIDs()
     }
     
-    func addMailAddressForKey(mailAddress: String, keyID: String) {
+    func addMailAddressForKey(_ mailAddress: String, keyID: String) {
         self.addMailAddressesForKey([mailAddress], keyID: keyID)
     }
     
-    func addMailAddressesForKey(mailAddresses: [String], keyID: String) {
+    func addMailAddressesForKey(_ mailAddresses: [String], keyID: String) {
         self.keyManager.addMailAddressesForKey(mailAddresses, keyID: keyID)
     }
     
-    func removeMailAddressForKey(mailaddress: String, keyID: String){
+    func removeMailAddressForKey(_ mailaddress: String, keyID: String){
         self.removeMailAddressesForKey([mailaddress], keyID: keyID)
     }
     
-    func removeMailAddressesForKey(mailaddresses: [String], keyID: String){
+    func removeMailAddressesForKey(_ mailaddresses: [String], keyID: String){
         self.keyManager.removeMailAddressesForKey(mailaddresses, keyID: keyID)
     }
     
-    func keyIDExists(keyID: String) -> Bool {
+    func keyIDExists(_ keyID: String) -> Bool {
         return self.keyManager.keyIDExists(keyID)
     }
     
     //TODO
-    func keyOfThisEncryption(keyData: NSData) -> Bool? {
+    func keyOfThisEncryption(_ keyData: Data) -> Bool? {
         return nil
     }
     
-    func autocryptHeader(adr: String) -> String {
+    func autocryptHeader(_ adr: String) -> String {
         let keyId = self.getActualKeyID(adr)
         let key = self.getKey(keyId!) as! PGPKeyWrapper
         let pgpManger = self.keyManager
-        var string = "to=" + adr + "; type=p;prefer-encrypted=" + (UserManager.loadUserValue(Attribute.PrefEncryption) as! String) + ";key="
+        var string = "to=" + adr + "; type=p;prefer-encrypted=" + (UserManager.loadUserValue(Attribute.prefEncryption) as! String) + ";key="
         if let keyBase64 = pgpManger.pgp.exportKeyWithoutArmor(key.key){
          string = string + keyBase64
         }
@@ -489,7 +495,7 @@ class PGPEncryption : Encryption {
     
     
     //the libary (ObjectivePGP) we use has a different definition of keyID than we have. their keyID is calculated outof the key. We take their keyID and add a index in the end to handle collisions
-    private func getLibaryKeyIDOverlap(libaryKeyID: String, ourKeyIDs: [String]) -> [String] {
+    private func getLibaryKeyIDOverlap(_ libaryKeyID: String, ourKeyIDs: [String]) -> [String] {
         var returnValue: [String] = []
         for ourKeyID in ourKeyIDs {
             if ourKeyID.hasPrefix(libaryKeyID) {
diff --git a/enzevalos_iphone/PGPKeyManagement.swift b/enzevalos_iphone/PGPKeyManagement.swift
index aaee817baf9b87e7c7c67f7e656829245234da63..6b63ea04992c395eceae81b6442e1e26320c8ddc 100644
--- a/enzevalos_iphone/PGPKeyManagement.swift
+++ b/enzevalos_iphone/PGPKeyManagement.swift
@@ -22,59 +22,59 @@ class PGPKeyManagement {
         //get or create keyIDs
         var data = self.encryptionHandler.getPersistentData("keyIDs", encryptionType: self.encryptionType)
         if let unwrappedData = data {
-            self.keyIDs = (NSKeyedUnarchiver.unarchiveObjectWithData(unwrappedData) as! NSDictionary) as! [String: [String]]
+            self.keyIDs = (NSKeyedUnarchiver.unarchiveObject(with: unwrappedData) as! NSDictionary) as! [String: [String]]
         }
         else {
-            data = NSKeyedArchiver.archivedDataWithRootObject(keyIDs)
+            data = NSKeyedArchiver.archivedData(withRootObject: keyIDs)
             self.encryptionHandler.addPersistentData(data!, searchKey: "keyIDs", encryptionType: self.encryptionType)
         }
         data = self.encryptionHandler.getPersistentData("addresses", encryptionType: self.encryptionType)
         if let unwrappedData = data {
-            self.addresses = (NSKeyedUnarchiver.unarchiveObjectWithData(unwrappedData) as! NSDictionary) as! [String: [String]]
+            self.addresses = (NSKeyedUnarchiver.unarchiveObject(with: unwrappedData) as! NSDictionary) as! [String: [String]]
         }
         else {
-            data = NSKeyedArchiver.archivedDataWithRootObject(addresses)
+            data = NSKeyedArchiver.archivedData(withRootObject: addresses)
             self.encryptionHandler.addPersistentData(data!, searchKey: "addresses", encryptionType: self.encryptionType)
         }
         data = self.encryptionHandler.getPersistentData("actualPrivateKey", encryptionType: self.encryptionType)
         if let unwrappedData = data {
-            self.actualPrivateKey = NSKeyedUnarchiver.unarchiveObjectWithData(unwrappedData) as? String
+            self.actualPrivateKey = NSKeyedUnarchiver.unarchiveObject(with: unwrappedData) as? String
         }
         else {
             self.actualPrivateKey = nil
         }
         data = self.encryptionHandler.getPersistentData("privateKeys", encryptionType: self.encryptionType)
         if let unwrappedData = data {
-            self.privateKeys = NSKeyedUnarchiver.unarchiveObjectWithData(unwrappedData) as! [String]
+            self.privateKeys = NSKeyedUnarchiver.unarchiveObject(with: unwrappedData) as! [String]
         }
         else {
             self.privateKeys = []
-            let insertData = NSKeyedArchiver.archivedDataWithRootObject(self.privateKeys)
+            let insertData = NSKeyedArchiver.archivedData(withRootObject: self.privateKeys)
             encryptionHandler.addPersistentData(insertData, searchKey: "privateKeys", encryptionType: self.encryptionType)
         }
         self.pgp = ObjectivePGP.init()
     }
     
-    func getMaxIndex(fingerprint: String) -> Int64 {
+    func getMaxIndex(_ fingerprint: String) -> Int64 {
         var index : Int64 = 0
         if let indexData = encryptionHandler.getPersistentData(fingerprint+"-index", encryptionType: self.encryptionType){
-            indexData.getBytes(&index, length: sizeof(Int64))
+            (indexData as NSData).getBytes(&index, length: sizeof(Int64))
         }
         
         return index
     }
     
-    func addKey(key: PGPKeyWrapper, forMailAddresses: [String]) -> String{
+    func addKey(_ key: PGPKeyWrapper, forMailAddresses: [String]) -> String{
         var index : Int64 = 0
         let searchKey = key.key.keyID.longKeyString+"-index"
         var existent = false
         if let indexData = encryptionHandler.getPersistentData(searchKey, encryptionType: self.encryptionType){
             existent = true
-            indexData.getBytes(&index, length: sizeof(Int64))
+            (indexData as NSData).getBytes(&index, length: sizeof(Int64))
         }
         
         index += 1
-        let indexData = NSData(bytes: &index, length: sizeof(Int64))
+        let indexData = Data(bytes: UnsafePointer<UInt8>(&index), count: sizeof(Int64))
         if !existent {
             encryptionHandler.addPersistentData(indexData, searchKey: searchKey, encryptionType: self.encryptionType)
         }
@@ -85,7 +85,7 @@ class PGPKeyManagement {
         let keyID = key.key.keyID.longKeyString+"-"+String(index)
         key.setOnceKeyID(keyID)
         
-        let data = NSKeyedArchiver.archivedDataWithRootObject(key)
+        let data = NSKeyedArchiver.archivedData(withRootObject: key)
         //key-ID should be created once
         //encryptionHandler.addPersistentData(data, searchKey: key.keyID, encryptionType: self.encryptionType)
         
@@ -112,24 +112,24 @@ class PGPKeyManagement {
     }
     
     
-    func updateKey(key: PGPKeyWrapper) {
+    func updateKey(_ key: PGPKeyWrapper) {
         if encryptionHandler.hasPersistentData(key.keyID, encryptionType: self.encryptionType) {
-            let keyData = NSKeyedArchiver.archivedDataWithRootObject(key)
+            let keyData = NSKeyedArchiver.archivedData(withRootObject: key)
             encryptionHandler.replacePersistentData(key.keyID, replacementData: keyData, encryptionType: self.encryptionType)
             return
         }
     }
     
-    func findPublicKeyInBase64(key: PGPKeyWrapper)-> String{
+    func findPublicKeyInBase64(_ key: PGPKeyWrapper)-> String{
         if let data = self.pgp.exportKeyWithoutArmor(key.key){
             return data
         }
         return ""
     }
     
-    func addMailAddressesForKey(mailAddresses: [String], keyID: String){
+    func addMailAddressesForKey(_ mailAddresses: [String], keyID: String){
         for addr in mailAddresses{
-            let mailAddress = addr.lowercaseString
+            let mailAddress = addr.lowercased()
             //insert keyID in keyIDs
             if var keys = keyIDs[mailAddress]{
                 if !keys.contains(keyID) {
@@ -154,20 +154,20 @@ class PGPKeyManagement {
         saveDictionarys()
     }
     
-    func removeMailAddressesForKey(mailAddresses: [String], keyID: String) {
+    func removeMailAddressesForKey(_ mailAddresses: [String], keyID: String) {
         for addr in mailAddresses{
-            let mailAddress = addr.lowercaseString
+            let mailAddress = addr.lowercased()
             //remove keyID outof keyIDs
             if var keys = keyIDs[mailAddress]{
                 if keys.contains(keyID) {
-                    keys.removeAtIndex(keys.indexOf(keyID)!)
+                    keys.remove(at: keys.index(of: keyID)!)
                     keyIDs[mailAddress] = keys
                 }
             }
             //remove mailAddress outof addresses
             if var mAddresses = addresses[keyID]{
                 if mAddresses.contains(mailAddress) {
-                    mAddresses.removeAtIndex(mAddresses.indexOf(mailAddress)!)
+                    mAddresses.remove(at: mAddresses.index(of: mailAddress)!)
                     addresses[keyID] = mAddresses
                 }
             }
@@ -175,11 +175,11 @@ class PGPKeyManagement {
         saveDictionarys()
     }
     
-    func getKeyIDsForMailAddress(mailAddress: String) -> [String]?{
+    func getKeyIDsForMailAddress(_ mailAddress: String) -> [String]?{
         return keyIDs[mailAddress]
     }
     
-    func getActualKeyIDForMailaddress(mailaddress: String) -> String? {
+    func getActualKeyIDForMailaddress(_ mailaddress: String) -> String? {
         return keyIDs[mailaddress]?.last
     }
     
@@ -196,19 +196,19 @@ class PGPKeyManagement {
         return self.privateKeys
     }
     
-    func getKey(keyID: String) -> PGPKeyWrapper? {
+    func getKey(_ keyID: String) -> PGPKeyWrapper? {
         if let data = (encryptionHandler.getPersistentData(keyID, encryptionType: self.encryptionType)) {
-            let keywrapper = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? PGPKeyWrapper
+            let keywrapper = NSKeyedUnarchiver.unarchiveObject(with: data) as? PGPKeyWrapper
             return keywrapper
         }
         return nil
     }
     
-    func getMailAddressesForKeyID(keyID: String) -> [String]?{
+    func getMailAddressesForKeyID(_ keyID: String) -> [String]?{
         return addresses[keyID]
     }
     
-    func keyIDExists(keyID: String) -> Bool {
+    func keyIDExists(_ keyID: String) -> Bool {
         if let addr = addresses[keyID] {
             return addr != []
         }
@@ -216,7 +216,7 @@ class PGPKeyManagement {
     }
     
     //if the actualPrivateKey is removed a old key is set as actualPrivateKey, if availiable
-    func removeKey(keyID: String) {
+    func removeKey(_ keyID: String) {
         removePrivateKey(keyID)
         
         var addrs: [String] = []
@@ -227,8 +227,8 @@ class PGPKeyManagement {
         encryptionHandler.deletePersistentData(keyID, encryptionType: self.encryptionType)
     }
     
-    private func cleanIndex(keyID: String) {
-        let index = keyID.componentsSeparatedByString("-")[0]+"-index"
+    private func cleanIndex(_ keyID: String) {
+        let index = keyID.components(separatedBy: "-")[0]+"-index"
         encryptionHandler.deletePersistentData(index, encryptionType: self.encryptionType)
     }
     
@@ -241,7 +241,7 @@ class PGPKeyManagement {
         self.actualPrivateKey = nil
         encryptionHandler.deletePersistentData("actualPrivateKey", encryptionType: self.encryptionType)
         encryptionHandler.deletePersistentData("privateKeys", encryptionType: self.encryptionType)
-        let insertData = NSKeyedArchiver.archivedDataWithRootObject(self.privateKeys)
+        let insertData = NSKeyedArchiver.archivedData(withRootObject: self.privateKeys)
         encryptionHandler.addPersistentData(insertData, searchKey: "privateKeys", encryptionType: self.encryptionType)
         for keyID in addresses.keys {
             self.removeKey(keyID)
@@ -276,19 +276,19 @@ class PGPKeyManagement {
     
     
     private func saveDictionarys(){
-        var data = NSKeyedArchiver.archivedDataWithRootObject(keyIDs as NSDictionary)
+        var data = NSKeyedArchiver.archivedData(withRootObject: keyIDs as NSDictionary)
         encryptionHandler.replacePersistentData("keyIDs", replacementData: data, encryptionType: self.encryptionType)
-        data = NSKeyedArchiver.archivedDataWithRootObject(addresses as NSDictionary)
+        data = NSKeyedArchiver.archivedData(withRootObject: addresses as NSDictionary)
         encryptionHandler.replacePersistentData("addresses", replacementData: data, encryptionType: self.encryptionType)
     }
     
-    private func addPrivateKey(key: PGPKeyWrapper) {
-        if key.key.type == PGPKeyType.Secret {
+    private func addPrivateKey(_ key: PGPKeyWrapper) {
+        if key.key.type == PGPKeyType.secret {
             privateKeys.append(key.keyID)
-            var data = NSKeyedArchiver.archivedDataWithRootObject(privateKeys)
+            var data = NSKeyedArchiver.archivedData(withRootObject: privateKeys)
             encryptionHandler.replacePersistentData("privateKeys", replacementData: data, encryptionType: self.encryptionType)
             actualPrivateKey = key.keyID
-            data = NSKeyedArchiver.archivedDataWithRootObject(actualPrivateKey!)
+            data = NSKeyedArchiver.archivedData(withRootObject: actualPrivateKey!)
             if encryptionHandler.hasPersistentData("actualPrivateKey", encryptionType: self.encryptionType) {
                 encryptionHandler.replacePersistentData("actualPrivateKey", replacementData: data, encryptionType: self.encryptionType)
             }
@@ -299,18 +299,18 @@ class PGPKeyManagement {
         }
     }
     
-    private func removePrivateKey(keyID: String) {
+    private func removePrivateKey(_ keyID: String) {
         if privateKeys.contains(keyID) {
-            privateKeys.removeAtIndex(privateKeys.indexOf(keyID)!)
+            privateKeys.remove(at: privateKeys.index(of: keyID)!)
             actualPrivateKey = privateKeys.last
             if let key = actualPrivateKey {
-                let data = NSKeyedArchiver.archivedDataWithRootObject(key)
+                let data = NSKeyedArchiver.archivedData(withRootObject: key)
                 encryptionHandler.replacePersistentData("actualPrivateKey", replacementData: data, encryptionType: self.encryptionType)
             }
             else {
                 encryptionHandler.deletePersistentData("actualPrivateKey", encryptionType: self.encryptionType)
             }
-            let data = NSKeyedArchiver.archivedDataWithRootObject(privateKeys)
+            let data = NSKeyedArchiver.archivedData(withRootObject: privateKeys)
             encryptionHandler.addPersistentData(data, searchKey: "privateKeys", encryptionType: self.encryptionType)
             self.useOnlyActualPrivateKey()
         }
diff --git a/enzevalos_iphone/PGPKeyWrapper.swift b/enzevalos_iphone/PGPKeyWrapper.swift
index 6d9ea25894f3166b1fbecc26adf302e67fb81d57..fb3b6d19b45da06f057c76438495adb7431c430e 100644
--- a/enzevalos_iphone/PGPKeyWrapper.swift
+++ b/enzevalos_iphone/PGPKeyWrapper.swift
@@ -8,7 +8,7 @@
 
 import Foundation
 
-public class PGPKeyWrapper : NSObject, KeyWrapper {
+open class PGPKeyWrapper : NSObject, KeyWrapper {
     
     let key: PGPKey /*{
         set (newKey) {
@@ -28,24 +28,24 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
     
     //private(set) var alternativeOldKeys: [KeyWrapper]?
     
-    public var expireDate: NSDate?{
+    open var expireDate: Date?{
         get{
             // Expire date is not speficied for PublicKeyPacket V4.
             // See: https://tools.ietf.org/html/rfc4880#section-5.5.1.1
             if let publicKey = publicKeyPacket{
                 // TODO: Consider other packets?
-                if publicKey.V3validityPeriod <= 0{
+                if publicKey.v3validityPeriod <= 0{
                     return nil
                 }
                 else{
-                    return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: Int(publicKey.V3validityPeriod), toDate: publicKey.createDate, options: [])
+                    return (Calendar.current as NSCalendar).date(byAdding: .day, value: Int(publicKey.v3validityPeriod), to: publicKey.createDate, options: [])
                 }
             }
             return nil
         }
     }
     
-    public var creationDate: NSDate{
+    open var creationDate: Date{
         get{
             // TODO: Consider other packets?
             if let publicKey = publicKeyPacket{
@@ -73,42 +73,42 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
     }
     
     
-    public var revoked: Bool{
+    open var revoked: Bool{
         didSet {
-            self.revokeTime = NSDate.init()
+            self.revokeTime = Date.init()
             self.keyManager.updateKey(self)
         }
     }
     
-    public private(set) var revokeTime: NSDate?
+    open fileprivate(set) var revokeTime: Date?
     
     //choose Int8 here?
-    public var trustlevel: Int{
+    open var trustlevel: Int{
         didSet {
             self.keyManager.updateKey(self)
         }
     } //negative misstrust; zero neutral; positive trust
     
-    public var verified: Bool{
+    open var verified: Bool{
         didSet {
-            self.verifyTime = NSDate.init()
+            self.verifyTime = Date.init()
             self.keyManager.updateKey(self)
         }
     }
     
-    public private(set) var verifyTime: NSDate?
-    public let discoveryTime: NSDate
+    open fileprivate(set) var verifyTime: Date?
+    open let discoveryTime: Date
     
     //TODO
-    public let discoveryMailUID: UInt64?
+    open let discoveryMailUID: UInt64?
     
-    public let type: EncryptionType = EncryptionType.PGP
+    open let type: EncryptionType = EncryptionType.PGP
 
-    public private(set) var keyID: String //will look like key.longKeyString+"-1" for the key with this longKeyString at index 1
+    open fileprivate(set) var keyID: String //will look like key.longKeyString+"-1" for the key with this longKeyString at index 1
     
-    private let keyManager: PGPKeyManagement
+    fileprivate let keyManager: PGPKeyManagement
     
-    public var mailAddresses : [String]? {
+    open var mailAddresses : [String]? {
         get {
             return self.keyManager.getMailAddressesForKeyID(self.keyID)
         }
@@ -120,8 +120,8 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
                 if var addrs = mailAddresses {
                     for entry in arr {
                         if addrs.contains(entry){
-                            addrs.removeAtIndex(addrs.indexOf(entry)!)
-                            arr.removeAtIndex(arr.indexOf(entry)!)
+                            addrs.remove(at: addrs.index(of: entry)!)
+                            arr.remove(at: arr.index(of: entry)!)
                         }
                     }
                     deleted = addrs
@@ -142,7 +142,7 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
     //KeyIDs from previous keys, that signed the actual key
     //public var predecessorsKeyID: [String]?
     
-    public var mailAddressesInKey: [String]? {
+    open var mailAddressesInKey: [String]? {
         get {
             var array: [String] = []
             for user:PGPUser in key.users as NSArray as! [PGPUser]{
@@ -158,7 +158,7 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
     init(key: PGPKey, mailAddresses: [String], discoveryMailUID: UInt64?, keyManager: PGPKeyManagement){
         self.key = key
         self.keyManager = keyManager
-        self.discoveryTime = NSDate.init()
+        self.discoveryTime = Date.init()
         self.discoveryMailUID = discoveryMailUID
         self.keyID = ""
         revoked = false
@@ -172,40 +172,40 @@ public class PGPKeyWrapper : NSObject, KeyWrapper {
     required public init(coder: NSCoder){
         let enc : PGPEncryption = EnzevalosEncryptionHandler.getEncryption(self.type)! as! PGPEncryption
         keyManager = (enc as PGPEncryption).getPGPKeyManagement()//coder.decodeObjectForKey("keyManager") as! PGPKeyManagement
-        key = keyManager.pgp.keysFromData(coder.decodeObjectForKey("key") as! NSData)![0]
-        revoked = coder.decodeBoolForKey("revoked")
-        revokeTime = coder.decodeObjectForKey("revokeTime") as! NSDate?
-        trustlevel = coder.decodeIntegerForKey("trustlevel")
-        verified = coder.decodeBoolForKey("verified")
-        verifyTime = coder.decodeObjectForKey("verifyTime") as! NSDate?
-        keyID = coder.decodeObjectForKey("keyID") as! String
-        if let dmailUID = coder.decodeObjectForKey("discoveryMailUID"){
-            self.discoveryMailUID = (dmailUID as! NSNumber).unsignedLongLongValue
+        key = keyManager.pgp.keys(from: coder.decodeObject(forKey: "key") as! Data)![0]
+        revoked = coder.decodeBool(forKey: "revoked")
+        revokeTime = coder.decodeObject(forKey: "revokeTime") as! Date?
+        trustlevel = coder.decodeInteger(forKey: "trustlevel")
+        verified = coder.decodeBool(forKey: "verified")
+        verifyTime = coder.decodeObject(forKey: "verifyTime") as! Date?
+        keyID = coder.decodeObject(forKey: "keyID") as! String
+        if let dmailUID = coder.decodeObject(forKey: "discoveryMailUID"){
+            self.discoveryMailUID = (dmailUID as! NSNumber).uint64Value
         }
         else {
             self.discoveryMailUID = nil
         }
-        discoveryTime = coder.decodeObjectForKey("discoveryTime") as! NSDate
+        discoveryTime = coder.decodeObject(forKey: "discoveryTime") as! Date
     }
     
-    public func setOnceKeyID (keyID: String) {
+    open func setOnceKeyID (_ keyID: String) {
         if self.keyID == "" {
             self.keyID = keyID
         }
     }
     
-    public func encodeWithCoder(coder: NSCoder){
-        coder.encodeObject((try? key.export())!, forKey: "key")
-        coder.encodeBool(revoked, forKey: "revoked")
-        coder.encodeObject(revokeTime, forKey: "revokeTime")
-        coder.encodeInteger(trustlevel, forKey: "trustlevel")
-        coder.encodeBool(verified, forKey: "verified")
-        coder.encodeObject(verifyTime, forKey: "verifyTime")
+    open func encodeWithCoder(_ coder: NSCoder){
+        coder.encode((try? key.export())!, forKey: "key")
+        coder.encode(revoked, forKey: "revoked")
+        coder.encode(revokeTime, forKey: "revokeTime")
+        coder.encode(trustlevel, forKey: "trustlevel")
+        coder.encode(verified, forKey: "verified")
+        coder.encode(verifyTime, forKey: "verifyTime")
         if let dmailUID = discoveryMailUID {
-            coder.encodeObject(NSNumber.init(unsignedLongLong: dmailUID), forKey: "discoveryMailUID")
+            coder.encode(NSNumber.init(value: dmailUID as UInt64), forKey: "discoveryMailUID")
         }
-        coder.encodeObject(keyID, forKey: "keyID")
-        coder.encodeObject(discoveryTime, forKey: "discoveryTime")
+        coder.encode(keyID, forKey: "keyID")
+        coder.encode(discoveryTime, forKey: "discoveryTime")
     }
     
 }
diff --git a/enzevalos_iphone/PGPTemporaryDecryptionObject.swift b/enzevalos_iphone/PGPTemporaryDecryptionObject.swift
index 7e1f2adf18a27ec3fee2fdbb513b7afbc0d014e1..dffe1418fa59991c49079013979ab6bd7c994b8d 100644
--- a/enzevalos_iphone/PGPTemporaryDecryptionObject.swift
+++ b/enzevalos_iphone/PGPTemporaryDecryptionObject.swift
@@ -10,9 +10,9 @@
 class PGPTemporaryDecryptionObject {
     let onePassSignaturePacket: PGPOnePassSignaturePacket
     let signaturePacket: PGPSignaturePacket
-    let plaintextData: NSData?
+    let plaintextData: Data?
     
-    init(onePassSignaturePacket: PGPOnePassSignaturePacket, signaturePacket: PGPSignaturePacket, plaintextData: NSData?){
+    init(onePassSignaturePacket: PGPOnePassSignaturePacket, signaturePacket: PGPSignaturePacket, plaintextData: Data?){
         self.onePassSignaturePacket = onePassSignaturePacket
         self.signaturePacket = signaturePacket
         self.plaintextData = plaintextData
diff --git a/enzevalos_iphone/Providers.swift b/enzevalos_iphone/Providers.swift
index b3a39c46c4d0b11008de9dc68f5dc076d70fd503..74394c407ff45920b4c60872ff95f3c319ddf08d 100644
--- a/enzevalos_iphone/Providers.swift
+++ b/enzevalos_iphone/Providers.swift
@@ -11,13 +11,23 @@ enum Provider : String {
 }
 
 class Providers {
-    static let config: [Provider : [Attribute : AnyObject?]] = [
-        Provider.WEB : [.SMTPHostname : "smtp.web.de", .SMTPPort : 587, .IMAPHostname : "imap.web.de", .IMAPPort : 993, .IMAPConnectionType: MCOConnectionType.TLS.rawValue, .IMAPAuthType: MCOAuthType.SASLPlain.rawValue, .SMTPConnectionType: MCOConnectionType.StartTLS.rawValue, .SMTPAuthType: MCOAuthType.SASLPlain.rawValue],
-        Provider.FU : [.SMTPHostname : "mail.zedat.fu-berlin.de", .SMTPPort : 587, .IMAPHostname : "mail.zedat.fu-berlin.de", .IMAPPort : 993, .IMAPConnectionType: MCOConnectionType.TLS.rawValue, .IMAPAuthType: MCOAuthType.SASLPlain.rawValue, .SMTPConnectionType: MCOConnectionType.StartTLS.rawValue, .SMTPAuthType: MCOAuthType.SASLPlain.rawValue],
-        Provider.ZEDAT : [.SMTPHostname : "mail.zedat.fu-berlin.de", .SMTPPort : 587, .IMAPHostname : "mail.zedat.fu-berlin.de", .IMAPPort : 143, .IMAPConnectionType: MCOConnectionType.StartTLS.rawValue, .IMAPAuthType: MCOAuthType.SASLPlain.rawValue, .SMTPConnectionType: MCOConnectionType.TLS.rawValue, .SMTPAuthType: MCOAuthType.SASLPlain.rawValue],
-        Provider.ENZEVALOS : [.SMTPHostname : "mail.enzevalos.de", .SMTPPort : 465, .IMAPHostname : "mail.enzevalos.de", .IMAPPort : 993, .IMAPConnectionType: MCOConnectionType.TLS.rawValue, .IMAPAuthType: MCOAuthType.SASLPlain.rawValue, .SMTPConnectionType: MCOConnectionType.TLS.rawValue, .SMTPAuthType: MCOAuthType.SASLPlain.rawValue]]
+    static let config: [Provider : [Attribute : AnyObject?]] = createConfig()
+
+        /*Provider.WEB : [.smtpHostname : "smtp.web.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "imap.web.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?],
+        Provider.FU : [.smtpHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?],
+        Provider.ZEDAT : [.smtpHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .imapPort : 143 as AnyObject?, .imapConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?],
+        Provider.ENZEVALOS : [.smtpHostname : "mail.enzevalos.de" as AnyObject?, .smtpPort : 465 as AnyObject?, .imapHostname : "mail.enzevalos.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?]*/
+    
+    static func createConfig() -> [Provider : [Attribute : AnyObject?]] {
+        var config: [Provider : [Attribute : AnyObject?]] = [:]
+        config.updateValue([.smtpHostname : "smtp.web.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "imap.web.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?], forKey: Provider.WEB)
+        config.updateValue([.smtpHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?], forKey: Provider.FU)
+        config.updateValue([.smtpHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .smtpPort : 587 as AnyObject?, .imapHostname : "mail.zedat.fu-berlin.de" as AnyObject?, .imapPort : 143 as AnyObject?, .imapConnectionType: MCOConnectionType.startTLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?], forKey: Provider.ZEDAT)
+        config.updateValue([.smtpHostname : "mail.enzevalos.de" as AnyObject?, .smtpPort : 465 as AnyObject?, .imapHostname : "mail.enzevalos.de" as AnyObject?, .imapPort : 993 as AnyObject?, .imapConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .imapAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?, .smtpConnectionType: MCOConnectionType.TLS.rawValue as AnyObject?, .smtpAuthType: MCOAuthType.saslPlain.rawValue as AnyObject?], forKey: Provider.ENZEVALOS)
+        return config
+    }
     
-    static func setValues(provider: Provider) {
+    static func setValues(_ provider: Provider) {
         for key in (config[provider]?.keys)! {
             UserManager.storeUserValue(config[provider]![key]!, attribute: key)
         }
diff --git a/enzevalos_iphone/ReadVENDelegate.swift b/enzevalos_iphone/ReadVENDelegate.swift
index ba256fbb04d8a2b864f2a0f5b3af132690ac4f61..24e5558426a4a2511802d83e21dad878da89bc58 100644
--- a/enzevalos_iphone/ReadVENDelegate.swift
+++ b/enzevalos_iphone/ReadVENDelegate.swift
@@ -10,23 +10,23 @@ import Foundation
 import VENTokenField
 
 class ReadVENDelegate: NSObject, VENTokenFieldDataSource {
-    var tappedWhenSelectedFunc: (String -> Void)? = nil
+    var tappedWhenSelectedFunc: ((String) -> Void)? = nil
     weak var tableView: UITableView?
 
-    init(tappedWhenSelectedFunc: (String -> Void)? = nil, mailTokens: [String]? = nil, textTokens: [String]? = nil, tableView: UITableView? = nil) {
+    init(tappedWhenSelectedFunc: ((String) -> Void)? = nil, mailTokens: [String]? = nil, textTokens: [String]? = nil, tableView: UITableView? = nil) {
         self.tappedWhenSelectedFunc = tappedWhenSelectedFunc
         self.tableView = tableView
     }
 
-    func tokenField(tokenField: VENTokenField, titleForTokenAtIndex index: UInt) -> String {
+    func tokenField(_ tokenField: VENTokenField, titleForTokenAt index: UInt) -> String {
         return tokenField.textTokens[Int(index)] as! String
     }
 
-    func numberOfTokensInTokenField(tokenField: VENTokenField) -> UInt {
+    func numberOfTokens(in tokenField: VENTokenField) -> UInt {
         return UInt((tokenField.textTokens.count))
     }
 
-    func tokenFieldCollapsedText(tokenField: VENTokenField) -> String {
+    func tokenFieldCollapsedText(_ tokenField: VENTokenField) -> String {
         if tokenField.textTokens.count > 1 {
             return "\(tokenField.textTokens.firstObject!) \(NSLocalizedString("and", comment: "and")) \(tokenField.textTokens.count - 1) \(NSLocalizedString("more", comment: "more"))"
         }
@@ -35,48 +35,48 @@ class ReadVENDelegate: NSObject, VENTokenFieldDataSource {
 }
 
 extension ReadVENDelegate: VENTokenFieldDelegate {
-    func tokenField(tokenField: VENTokenField, didEnterText text: String) {
-        tokenField.textTokens.addObject(text.lowercaseString)
+    func tokenField(_ tokenField: VENTokenField, didEnterText text: String) {
+        tokenField.textTokens.add(text.lowercased())
     }
 
-    func tokenField(tokenField: VENTokenField, didEnterText text: String, mail email: String) {
-        tokenField.textTokens.addObject(text)
-        tokenField.mailTokens.addObject(email)
+    func tokenField(_ tokenField: VENTokenField, didEnterText text: String, mail email: String) {
+        tokenField.textTokens.add(text)
+        tokenField.mailTokens.add(email)
         tokenField.reloadData()
 //        tokenField.sendActionsForControlEvents(UIControlEvents.EditingDidEnd)
     }
 
-    func tokenField(tokenField: VENTokenField, didChangeContentHeight height: CGFloat) {
+    func tokenField(_ tokenField: VENTokenField, didChangeContentHeight height: CGFloat) {
         if let tableView = tableView {
-            let indexPath = NSIndexPath(forRow: 1, inSection: 0)
-            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
+            let indexPath = IndexPath(row: 1, section: 0)
+            tableView.reloadRows(at: [indexPath], with: .none)
         }
     }
 
-    func tokenFieldDidEndEditing(tokenField: VENTokenField) {
+    func tokenFieldDidEndEditing(_ tokenField: VENTokenField) {
 
     }
 
-    func tokenField(tokenField: VENTokenField, didDeleteTokenAtIndex index: UInt) {
+    func tokenField(_ tokenField: VENTokenField, didDeleteTokenAt index: UInt) {
 
     }
 
-    func tokenField(tokenField: VENTokenField, didChangeText text: String?) {
+    func tokenField(_ tokenField: VENTokenField, didChangeText text: String?) {
 
     }
 
-    func tokenFieldDidBeginEditing(tokenField: VENTokenField) {
+    func tokenFieldDidBeginEditing(_ tokenField: VENTokenField) {
 
     }
 
-    func tokenField(tokenField: VENTokenField, colorSchemeForTokenAtIndex index: UInt) -> UIColor {
+    func tokenField(_ tokenField: VENTokenField, colorSchemeForTokenAt index: UInt) -> UIColor {
         if EnzevalosEncryptionHandler.hasKey(DataHandler.handler.getContactByAddress(tokenField.mailTokens[Int(index)] as! String)) { //unfassbar langsam!
             return UIColor.init(red: 0, green: 122.0 / 255.0, blue: 1, alpha: 1)
         }
-        return UIColor.orangeColor()
+        return UIColor.orange
     }
 
-    func tokenField(tokenField: VENTokenField, didTappedTokenTwice index: UInt) {
+    func tokenField(_ tokenField: VENTokenField, didTappedTokenTwice index: UInt) {
         if let fun = tappedWhenSelectedFunc {
             fun(tokenField.mailTokens[Int(index)] as! String)
         }
diff --git a/enzevalos_iphone/ReadViewController.swift b/enzevalos_iphone/ReadViewController.swift
index 9ccce45e56a7e12df5c0b7af6ac8f5ac8f8d8824..0786756ada4b01eec1a8fb734276c1793a47fd1b 100644
--- a/enzevalos_iphone/ReadViewController.swift
+++ b/enzevalos_iphone/ReadViewController.swift
@@ -51,30 +51,30 @@ class ReadViewController: UITableViewController {
         senderTokenField.delegate = VENDelegate
         senderTokenField.dataSource = VENDelegate
         senderTokenField.toLabelText = "\(NSLocalizedString("From", comment: "From field")):"
-        senderTokenField.toLabelTextColor = UIColor.darkGrayColor()
+        senderTokenField.toLabelTextColor = UIColor.darkGray
         senderTokenField.readOnly = true
 
         toTokenField.delegate = VENDelegate
         toTokenField.dataSource = VENDelegate
         toTokenField.toLabelText = "\(NSLocalizedString("To", comment: "To field")):"
-        toTokenField.toLabelTextColor = UIColor.darkGrayColor()
+        toTokenField.toLabelTextColor = UIColor.darkGray
         toTokenField.setColorScheme(self.view.tintColor)
         toTokenField.readOnly = true
 
         // not possible to set in IB
-        SeperatorConstraint.constant = 1 / UIScreen.mainScreen().scale
-        infoCell.layoutMargins = UIEdgeInsetsZero
+        SeperatorConstraint.constant = 1 / UIScreen.main.scale
+        infoCell.layoutMargins = UIEdgeInsets.zero
 
         setUItoMail()
     }
 
-    override func viewWillAppear(animated: Bool) {
+    override func viewWillAppear(_ animated: Bool) {
         // NavigationBar color
         if let mail = mail {
             if mail.trouble {
                 self.navigationController?.navigationBar.barTintColor = ThemeManager.troubleMessageColor()
                 if !mail.showMessage {
-                    answerButton.enabled = false
+                    answerButton.isEnabled = false
                 }
                 navigationController?.navigationBar
             } else if mail.isSecure {
@@ -85,20 +85,20 @@ class ReadViewController: UITableViewController {
         }
     }
 
-    override func willMoveToParentViewController(parent: UIViewController?) {
-        super.willMoveToParentViewController(parent)
+    override func willMove(toParentViewController parent: UIViewController?) {
+        super.willMove(toParentViewController: parent)
 
         if parent == nil {
-            UIView.animateWithDuration(0.3, animations: { self.navigationController?.navigationBar.barTintColor = ThemeManager.defaultColor })
+            UIView.animate(withDuration: 0.3, animations: { self.navigationController?.navigationBar.barTintColor = ThemeManager.defaultColor })
         }
     }
 
-    func showContact(email: String) {
+    func showContact(_ email: String) {
         let records = DataHandler.handler.getContactByAddress(email).records
         for r in records {
             for address in r.addresses {
                 if address.mailAddress == email && address.prefEnc == r.hasKey {
-                    performSegueWithIdentifier("showContact", sender: ["record": r, "email": email])
+                    performSegue(withIdentifier: "showContact", sender: ["record": r, "email": email])
                     return
                 }
             }
@@ -108,14 +108,14 @@ class ReadViewController: UITableViewController {
     }
 
     // set top seperator height
-    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
+    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         if section == 0 {
             return 8
         }
         return tableView.sectionHeaderHeight
     }
 
-    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
+    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         if indexPath.section == 0 && indexPath.row == 1 {
             if toTokenField.frame.height < 60 {
                 return 44.0
@@ -125,7 +125,7 @@ class ReadViewController: UITableViewController {
         return UITableViewAutomaticDimension
     }
 
-    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
+    override func numberOfSections(in tableView: UITableView) -> Int {
         if let mail = mail {
             if mail.trouble && mail.showMessage || !mail.trouble && !mail.isSecure && mail.from.contact.hasKey {
                 return 3
@@ -135,7 +135,7 @@ class ReadViewController: UITableViewController {
         return 2
     }
 
-    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         if section == 0 {
             return 3
         }
@@ -148,7 +148,7 @@ class ReadViewController: UITableViewController {
         return 1
     }
 
-    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
+    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         if indexPath.section == 0 {
             switch indexPath.row {
             case 0:
@@ -166,7 +166,7 @@ class ReadViewController: UITableViewController {
                         infoSymbol.text = "!"
                         infoSymbol.textColor = ThemeManager.troubleMessageColor()
                         infoHeadline.text = NSLocalizedString("corruptedHeadline", comment: "This mail is corrupted")
-                        infoHeadline.textColor = UIColor.blackColor()
+                        infoHeadline.textColor = UIColor.black
                         infoText.text = NSLocalizedString("corruptedText", comment: "This mail is corrupted")
                         infoCell.setNeedsLayout()
                         infoCell.layoutIfNeeded()
@@ -179,7 +179,7 @@ class ReadViewController: UITableViewController {
                     infoSymbol.text = "?"
                     infoSymbol.textColor = ThemeManager.uncryptedMessageColor()
                     infoHeadline.text = NSLocalizedString("encryptedBeforeHeadline", comment: "The sender has encrypted before")
-                    infoHeadline.textColor = UIColor.grayColor()
+                    infoHeadline.textColor = UIColor.gray
                     infoText.text = NSLocalizedString("encryptedBeforeText", comment: "The sender has encrypted before")
                     return infoCell
                 }
@@ -191,7 +191,7 @@ class ReadViewController: UITableViewController {
         return messageCell
     }
 
-    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
+    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
         if indexPath.section == 1 && indexPath.row == 0 {
             // get the tableview to use the correct height for this cell; please replace this with a better way if you know one
             tableView.beginUpdates()
@@ -199,58 +199,58 @@ class ReadViewController: UITableViewController {
         }
     }
 
-    @IBAction func showEmailButton(sender: UIButton) {
+    @IBAction func showEmailButton(_ sender: UIButton) {
         mail?.showMessage = true
 
         self.tableView.beginUpdates()
-        let path = NSIndexPath(forRow: 1, inSection: 1)
-        self.tableView.deleteRowsAtIndexPaths([path], withRowAnimation: .Fade)
-        self.tableView.insertSections(NSIndexSet(index: 2), withRowAnimation: .Fade)
+        let path = IndexPath(row: 1, section: 1)
+        self.tableView.deleteRows(at: [path], with: .fade)
+        self.tableView.insertSections(IndexSet(integer: 2), with: .fade)
         self.tableView.endUpdates()
 
-        answerButton.enabled = true
+        answerButton.isEnabled = true
     }
 
-    @IBAction func ignoreEmailButton(sender: AnyObject) {
-        navigationController?.popViewControllerAnimated(true)
+    @IBAction func ignoreEmailButton(_ sender: AnyObject) {
+        navigationController?.popViewController(animated: true)
     }
 
-    @IBAction func markUnreadButton(sender: AnyObject) {
+    @IBAction func markUnreadButton(_ sender: AnyObject) {
         mail?.isRead = false
-        navigationController?.popViewControllerAnimated(true)
+        navigationController?.popViewController(animated: true)
     }
 
-    @IBAction func deleteButton(sender: AnyObject) {
-        navigationController?.popViewControllerAnimated(true)
+    @IBAction func deleteButton(_ sender: AnyObject) {
+        navigationController?.popViewController(animated: true)
     }
 
-    @IBAction func iconButton(sender: AnyObject) {
+    @IBAction func iconButton(_ sender: AnyObject) {
         if let m = mail {
             let alert: UIAlertController
             let url: String
             if m.trouble {
-                alert = UIAlertController(title: NSLocalizedString("LetterDamaged", comment: "Modified email received")/*"Angerissener Brief"*/, message: NSLocalizedString("ReceiveDamagedInfo", comment: "Modefied email infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("LetterDamaged", comment: "Modified email received")/*"Angerissener Brief"*/, message: NSLocalizedString("ReceiveDamagedInfo", comment: "Modefied email infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/corrupted"
             } else if m.isSecure {
-                alert = UIAlertController(title: NSLocalizedString("Letter", comment: "letter label"), message: NSLocalizedString("ReceiveSecureInfo", comment: "Letter infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("Letter", comment: "letter label"), message: NSLocalizedString("ReceiveSecureInfo", comment: "Letter infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/letter"
             } else if m.isCorrectlySigned {
-                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoVerified", comment: "Postcard infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoVerified", comment: "Postcard infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/postcard_verified"
             } else if m.isEncrypted && !m.unableToDecrypt {
-                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoEncrypted", comment: "Postcard infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoEncrypted", comment: "Postcard infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/postcard_encrypted"
             } else if m.isEncrypted && m.unableToDecrypt {
-                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoDecryptionFailed", comment: "Postcard infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfoDecryptionFailed", comment: "Postcard infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/postcard_decryption_failed"
             } else {
-                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfo", comment: "Postcard infotext"), preferredStyle: .Alert)
+                alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "postcard label"), message: NSLocalizedString("ReceiveInsecureInfo", comment: "Postcard infotext"), preferredStyle: .alert)
                 url = "https://enzevalos.de/infos/postcard"
             }
-            alert.addAction(UIAlertAction(title: "Mehr Informationen", style: .Default, handler: { (action: UIAlertAction!) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: url)!) }))
-            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
-            dispatch_async(dispatch_get_main_queue(), {
-                self.presentViewController(alert, animated: true, completion: nil)
+            alert.addAction(UIAlertAction(title: "Mehr Informationen", style: .default, handler: { (action: UIAlertAction!) -> Void in UIApplication.shared.openURL(URL(string: url)!) }))
+            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
+            DispatchQueue.main.async(execute: {
+                self.present(alert, animated: true, completion: nil)
             })
         }
     }
@@ -259,11 +259,11 @@ class ReadViewController: UITableViewController {
         if let m = mail {
 
             // mark mail as read if viewcontroller is open for more than 1.5 sec
-            let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC)))
-            dispatch_after(delay, dispatch_get_main_queue()) {
+            let delay = DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
+            DispatchQueue.main.asyncAfter(deadline: delay) {
                 if let viewControllers = self.navigationController?.viewControllers {
                     for viewController in viewControllers {
-                        if viewController.isKindOfClass(ReadViewController) {
+                        if viewController.isKind(of: ReadViewController.self) {
                             m.isRead = true
                         }
                     }
@@ -303,7 +303,7 @@ class ReadViewController: UITableViewController {
             receivedTime.text = m.timeString
 
             if let subj = m.subject {
-                if subj.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).characters.count > 0 {
+                if subj.trimmingCharacters(in: CharacterSet.whitespaces).characters.count > 0 {
                     subject.text = subj
                 } else {
                     subject.text = NSLocalizedString("SubjectNo", comment: "This mail has no subject")
@@ -318,8 +318,8 @@ class ReadViewController: UITableViewController {
             }
             // NavigationBar Icon
             let iconView = UIImageView()
-            iconView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
-            iconView.contentMode = .ScaleAspectFit
+            iconView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
+            iconView.contentMode = .scaleAspectFit
             var icon: UIImage
             if m.trouble {
                 icon = IconsStyleKit.imageOfLetterCorrupted
@@ -329,22 +329,22 @@ class ReadViewController: UITableViewController {
                 icon = IconsStyleKit.imageOfPostcard
             }
             iconView.image = icon
-            iconButton.setImage(icon, forState: UIControlState.Normal)
+            iconButton.setImage(icon, for: UIControlState())
 
             print("enc: ", m.isEncrypted, ", unableDec: ", m.unableToDecrypt, ", signed: ", m.isSigned, ", correctlySig: ", m.isCorrectlySigned, ", oldPrivK: ", m.decryptedWithOldPrivateKey)
             EnzevalosEncryptionHandler.getEncryption(.PGP)?.decryptAndSignatureCheck(m)
         }
     }
 
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "answerTo" {
-            let navigationController = segue.destinationViewController as? UINavigationController
+            let navigationController = segue.destination as? UINavigationController
             let controller = navigationController?.topViewController as? SendViewController
             if controller != nil {
                 controller?.answerTo = mail
             }
         } else if segue.identifier == "showContact" {
-            let destinationVC = segue.destinationViewController as! ContactViewController
+            let destinationVC = segue.destination as! ContactViewController
             if let sender = sender {
                 destinationVC.keyRecord = (sender["record"] as! KeyRecord)
                 destinationVC.highlightEmail = (sender["email"] as! String)
diff --git a/enzevalos_iphone/Record.swift b/enzevalos_iphone/Record.swift
index dac24e914ac799a879d283a40b62a994b2c24c09..b3e757b3bc495de2c57e59329115a556b0320420 100644
--- a/enzevalos_iphone/Record.swift
+++ b/enzevalos_iphone/Record.swift
@@ -23,6 +23,6 @@ public protocol Record: Comparable {
     var addresses: [MailAddress] { get }
 
 
-    func addNewAddress(adr: MailAddress) -> Bool
-    func addNewMail(mail: Mail) -> Bool
+    func addNewAddress(_ adr: MailAddress) -> Bool
+    func addNewMail(_ mail: Mail) -> Bool
 }
diff --git a/enzevalos_iphone/RefreshControlExtension.swift b/enzevalos_iphone/RefreshControlExtension.swift
index 160a1bffbeea167706802a76430de29a32b59e58..0a6e51c5146bea3f29f712bc48c828a6afb17e50 100644
--- a/enzevalos_iphone/RefreshControlExtension.swift
+++ b/enzevalos_iphone/RefreshControlExtension.swift
@@ -15,6 +15,6 @@ extension UIRefreshControl {
             scrollView.setContentOffset(CGPoint(x: 0, y: scrollView.contentOffset.y - frame.height), animated: true)
         }
         beginRefreshing()
-        sendActionsForControlEvents(UIControlEvents.ValueChanged)
+        sendActions(for: UIControlEvents.valueChanged)
     }
 }
diff --git a/enzevalos_iphone/ReplaceSegue.swift b/enzevalos_iphone/ReplaceSegue.swift
index 171d0392a83a64a3705a853cb59322f274da3458..4aa51a31a338a83f82b7aa92eb2209427d843630 100644
--- a/enzevalos_iphone/ReplaceSegue.swift
+++ b/enzevalos_iphone/ReplaceSegue.swift
@@ -11,11 +11,11 @@ import UIKit
 class ReplaceSegue: UIStoryboardSegue {
     override func perform() {
 
-        if let navigationController = sourceViewController.navigationController {
+        if let navigationController = source.navigationController {
 
             var controllerStack = navigationController.viewControllers
-            let index = controllerStack.indexOf(sourceViewController)
-            controllerStack[index!] = destinationViewController
+            let index = controllerStack.index(of: source)
+            controllerStack[index!] = destination
 
             navigationController.setViewControllers(controllerStack, animated: true)
         }
diff --git a/enzevalos_iphone/SendViewController.swift b/enzevalos_iphone/SendViewController.swift
index 33c65b819c05be72a6444aec840c05e752dbb866..7fe8f469a6e67b1159e026cd072e3825778a0470 100644
--- a/enzevalos_iphone/SendViewController.swift
+++ b/enzevalos_iphone/SendViewController.swift
@@ -61,7 +61,7 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         setAnimation()
 
         textView.delegate = self
-        textView.font = UIFont.systemFontOfSize(17)
+        textView.font = UIFont.systemFont(ofSize: 17)
         textView.text = ""
 
         subjectText.toLabelText = NSLocalizedString("Subject", comment: "subject label") + ": "
@@ -69,12 +69,12 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         iconButton.addSubview(AnimatedSendIcon())
         toText.delegate = dataDelegate
         toText.dataSource = dataDelegate
-        toText.inputTextFieldKeyboardType = UIKeyboardType.EmailAddress
+        toText.inputTextFieldKeyboardType = UIKeyboardType.emailAddress
         toText.toLabelText = NSLocalizedString("To", comment: "to label") + ": "
         toText.setColorScheme(self.view.tintColor)
         toCollectionview.delegate = collectionDataDelegate
         toCollectionview.dataSource = collectionDataDelegate
-        toCollectionview.registerNib(UINib(nibName: "FrequentCell", bundle: nil), forCellWithReuseIdentifier: "frequent")
+        toCollectionview.register(UINib(nibName: "FrequentCell", bundle: nil), forCellWithReuseIdentifier: "frequent")
         toCollectionviewHeight.constant = 0
         ccText.delegate = dataDelegate
         ccText.dataSource = dataDelegate
@@ -82,7 +82,7 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         ccText.setColorScheme(self.view.tintColor)
         ccCollectionview.delegate = collectionDataDelegate
         ccCollectionview.dataSource = collectionDataDelegate
-        ccCollectionview.registerNib(UINib(nibName: "FrequentCell", bundle: nil), forCellWithReuseIdentifier: "frequent")
+        ccCollectionview.register(UINib(nibName: "FrequentCell", bundle: nil), forCellWithReuseIdentifier: "frequent")
         ccCollectionviewHeight.constant = 0
         //ccCollectionview.translatesAutoresizingMaskIntoConstraints = true
         //toCollectionview.translatesAutoresizingMaskIntoConstraints = true
@@ -98,8 +98,8 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         subjectText.setColorScheme(self.view.tintColor)
 
         //will always be thrown, when a token was editied
-        toText.addTarget(self, action: #selector(self.newInput(_:)), forControlEvents: UIControlEvents.EditingDidEnd)
-        ccText.addTarget(self, action: #selector(self.newInput(_:)), forControlEvents: UIControlEvents.EditingDidEnd)
+        toText.addTarget(self, action: #selector(self.newInput(_:)), for: UIControlEvents.editingDidEnd)
+        ccText.addTarget(self, action: #selector(self.newInput(_:)), for: UIControlEvents.editingDidEnd)
 
         if let to = toField {
             let ezCon = DataHandler.handler.getContactByAddress(to)
@@ -107,32 +107,32 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         } else if answerTo != nil {
             toText.delegate?.tokenField!(toText, didEnterText: (answerTo?.from.address)!)
             for r in (answerTo?.getReceivers())! {
-                if r.address != UserManager.loadUserValue(Attribute.UserAddr) as! String {
+                if r.address != UserManager.loadUserValue(Attribute.userAddr) as! String {
                     ccText.delegate?.tokenField!(ccText, didEnterText: r.address)
                 }
             }
             subjectText.setText(NSLocalizedString("Re", comment: "prefix for subjects of answered mails") + ": " + (answerTo?.subject!)!)
             textView.text = NSLocalizedString("mail from", comment: "describing who send the mail") + " "
-            textView.text.appendContentsOf((answerTo?.from.address)!)
-            textView.text.appendContentsOf(" " + NSLocalizedString("sent at", comment: "describing when the mail was send") + " " + (answerTo?.timeString)!)
-            textView.text.appendContentsOf("\n" + NSLocalizedString("to", comment: "describing adressee") + ": ")
-            textView.text.appendContentsOf(UserManager.loadUserValue(Attribute.UserAddr) as! String)
+            textView.text.append((answerTo?.from.address)!)
+            textView.text.append(" " + NSLocalizedString("sent at", comment: "describing when the mail was send") + " " + (answerTo?.timeString)!)
+            textView.text.append("\n" + NSLocalizedString("to", comment: "describing adressee") + ": ")
+            textView.text.append(UserManager.loadUserValue(Attribute.userAddr) as! String)
             if ccText.mailTokens.count > 0 {
-                textView.text.appendContentsOf(", ")
+                textView.text.append(", ")
             }
-            textView.text.appendContentsOf(ccText.mailTokens.componentsJoinedByString(", "))
-            textView.text.appendContentsOf("\n" + NSLocalizedString("subject", comment: "describing what subject was choosen") + ": " + (answerTo?.subject!)!)
+            textView.text.append(ccText.mailTokens.componentsJoined(by: ", "))
+            textView.text.append("\n" + NSLocalizedString("subject", comment: "describing what subject was choosen") + ": " + (answerTo?.subject!)!)
             if answerTo!.isEncrypted {
                 if answerTo?.decryptedBody != nil {
-                    textView.text.appendContentsOf("\n--------------------\n\n" + (answerTo?.decryptedBody)!)
+                    textView.text.append("\n--------------------\n\n" + (answerTo?.decryptedBody)!)
                 }
             } else {
-                textView.text.appendContentsOf("\n--------------------\n\n" + (answerTo?.body)!) //textView.text.appendContentsOf("\n"+NSLocalizedString("original message", comment: "describing contents of the original message")+": \n\n"+(answerTo?.body)!)
+                textView.text.append("\n--------------------\n\n" + (answerTo?.body)!) //textView.text.appendContentsOf("\n"+NSLocalizedString("original message", comment: "describing contents of the original message")+": \n\n"+(answerTo?.body)!)
             }
             textView.text = TextFormatter.insertBeforeEveryLine("> ", text: textView.text)
         }
 
-        let sepConst: CGFloat = 1 / UIScreen.mainScreen().scale
+        let sepConst: CGFloat = 1 / UIScreen.main.scale
         seperator1Height.constant = sepConst//0.5
         seperator2Height.constant = sepConst//0.5
         seperator3Height.constant = sepConst//0.5
@@ -143,21 +143,21 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
 
         textViewLeading.constant = seperator3Leading.constant - 4
 
-        ccText.inputTextFieldKeyboardType = UIKeyboardType.EmailAddress
+        ccText.inputTextFieldKeyboardType = UIKeyboardType.emailAddress
         scrollview.clipsToBounds = true
 
         tableview.delegate = tableDataDelegate
         tableview.dataSource = tableDataDelegate
-        tableview.registerNib(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "contacts")
+        tableview.register(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "contacts")
         tableviewHeight.constant = 0
 
 
-        let indexPath = NSIndexPath()
-        tableview.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
+        let indexPath = IndexPath()
+        tableview.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
 
         //register KeyBoardevents
-        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardOpen(_:)), name: UIKeyboardWillShowNotification, object: nil);
-        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardClose(_:)), name: UIKeyboardWillHideNotification, object: nil);
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardOpen(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
+        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardClose(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
 
         toText.tag = UIViewResolver.toText.rawValue
         ccText.tag = UIViewResolver.ccText.rawValue
@@ -230,19 +230,19 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         //---------------------------------------
     }
 
-    override func viewWillAppear(animated: Bool) {
+    override func viewWillAppear(_ animated: Bool) {
         updateNavigationBar()
     }
 
-    override func willMoveToParentViewController(parent: UIViewController?) {
-        super.willMoveToParentViewController(parent)
+    override func willMove(toParentViewController parent: UIViewController?) {
+        super.willMove(toParentViewController: parent)
 
         if parent == nil {
-            UIView.animateWithDuration(0.3, animations: { self.navigationController?.navigationBar.barTintColor = ThemeManager.defaultColor })
+            UIView.animate(withDuration: 0.3, animations: { self.navigationController?.navigationBar.barTintColor = ThemeManager.defaultColor })
         }
     }
 
-    @IBAction func iconButtonPressed(sender: AnyObject) {
+    @IBAction func iconButtonPressed(_ sender: AnyObject) {
         iconButton(sender)
     }
 
@@ -251,42 +251,42 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         // Dispose of any resources that can be recreated.
     }
 
-    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
+    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }
 
-    @IBAction func tapped(sender: UITapGestureRecognizer) {
+    @IBAction func tapped(_ sender: UITapGestureRecognizer) {
         //print(sender.description)
         //print(String(sender.view?.valueForKey("UILoggingName")))
         if LogHandler.logging {
-            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "tap", point: sender.locationOfTouch(sender.numberOfTouches() - 1, inView: self.view), /*debugDescription: sender.view.debugDescription,*/ comment: "")
+            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "tap", point: sender.location(ofTouch: sender.numberOfTouches - 1, in: self.view), /*debugDescription: sender.view.debugDescription,*/ comment: "")
         }
     }
 
-    @IBAction func panned(sender: UIPanGestureRecognizer) {
+    @IBAction func panned(_ sender: UIPanGestureRecognizer) {
         if LogHandler.logging {
-            if sender.state == .Began {
-                LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "beginPan", point: sender.locationInView(sender.view)/*CGPoint(x: 0,y: 0)*/, comment: String(sender.translationInView(sender.view)))
+            if sender.state == .began {
+                LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "beginPan", point: sender.location(in: sender.view)/*CGPoint(x: 0,y: 0)*/, comment: String(describing: sender.translation(in: sender.view)))
             }
-            if sender.state == .Ended {
-                LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "endPan", point: sender.locationInView(sender.view)/*CGPoint(x: 0,y: 0)*/, comment: String(sender.translationInView(sender.view)))
+            if sender.state == .ended {
+                LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "endPan", point: sender.location(in: sender.view)/*CGPoint(x: 0,y: 0)*/, comment: String(describing: sender.translation(in: sender.view)))
             }
         }
     }
 
-    @IBAction func swiped(sender: UISwipeGestureRecognizer) {
+    @IBAction func swiped(_ sender: UISwipeGestureRecognizer) {
         if LogHandler.logging {
-            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "swipe", point: sender.locationOfTouch(sender.numberOfTouches() - 1, inView: sender.view), comment: String(sender.direction))
+            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "swipe", point: sender.location(ofTouch: sender.numberOfTouches - 1, in: sender.view), comment: String(describing: sender.direction))
         }
     }
 
-    @IBAction func rotated(sender: UIRotationGestureRecognizer) {
+    @IBAction func rotated(_ sender: UIRotationGestureRecognizer) {
         if LogHandler.logging {
-            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "rotate", point: CGPoint(x: 0, y: 0), comment: String(sender.rotation))
+            LogHandler.doLog(UIViewResolver.resolve((sender.view?.tag)!), interaction: "rotate", point: CGPoint(x: 0, y: 0), comment: String(describing: sender.rotation))
         }
     }
 
-    func tokenField(tokenField: VENTokenField, didChangeText text: String?) {
+    func tokenField(_ tokenField: VENTokenField, didChangeText text: String?) {
         if LogHandler.logging {
             LogHandler.doLog(UIViewResolver.resolve(subjectText.tag), interaction: "changeText", point: CGPoint(x: 0, y: 0), comment: subjectText.inputText()!)
         }
@@ -298,13 +298,13 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         }
     }
 
-    func textViewDidChange(textView: UITextView) {
+    func textViewDidChange(_ textView: UITextView) {
         if LogHandler.logging {
             LogHandler.doLog(UIViewResolver.resolve(textView.tag), interaction: "changeText", point: CGPoint(x: 0, y: 0), comment: textView.text)
         }
     }
     
-    func tokenFieldDidEndEditing(tokenField: VENTokenField) {}
+    func tokenFieldDidEndEditing(_ tokenField: VENTokenField) {}
     
     func reloadCollectionViews() {
         //toCollectionview.collectionViewLayout.invalidateLayout()
@@ -351,12 +351,12 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         ccCollectionview.reloadData()
     }
     
-    func showContact(email: String) {
+    func showContact(_ email: String) {
         let records = DataHandler.handler.getContactByAddress(email).records
         for r in records {
             for address in r.addresses {
                 if address.mailAddress == email && address.prefEnc == r.hasKey {
-                    performSegueWithIdentifier("showContact", sender: ["record": r, "email": email])
+                    performSegue(withIdentifier: "showContact", sender: ["record": r, "email": email])
                     self.view.endEditing(true)
                     return
                 }
@@ -366,9 +366,9 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         //        performSegueWithIdentifier("showContact", sender: records.first)
     }
 
-    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
+    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.identifier == "showContact" {
-            let destinationVC = segue.destinationViewController as! ContactViewController
+            let destinationVC = segue.destination as! ContactViewController
             if let sender = sender {
                 destinationVC.keyRecord = (sender["record"] as! KeyRecord)
                 destinationVC.highlightEmail = (sender["email"] as! String)
@@ -376,20 +376,20 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         }
     }
 
-    func editName(tokenField: VENTokenField) {
+    func editName(_ tokenField: VENTokenField) {
         if let inText = tokenField.inputText() {
             if LogHandler.logging {
                 LogHandler.doLog(UIViewResolver.resolve(tokenField.tag), interaction: "changeText", point: CGPoint(x: 0, y: 0), comment: inText)
             }
             if inText != "" {
-                scrollview.scrollEnabled = false
+                scrollview.isScrollEnabled = false
                 scrollview.contentOffset = CGPoint(x: 0, y: tokenField.frame.origin.y - self.topLayoutGuide.length)
                 //print(tokenField.frame.origin.y, " ", tokenField.frame.maxY)
                 tableviewBegin.constant = tokenField.frame.maxY - tokenField.frame.origin.y
                 tableviewHeight.constant = keyboardY - tableviewBegin.constant - (self.navigationController?.navigationBar.frame.maxY)!
                 searchContacts(inText)
             } else {
-                scrollview.scrollEnabled = true
+                scrollview.isScrollEnabled = true
                 tableviewHeight.constant = 0
                 if tokenField == toText {
                     //toCollectionviewHeight.constant = 100
@@ -400,39 +400,39 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         }
     }
 
-    func insertName(name: String, address: String) {
-        if toText.isFirstResponder() {
+    func insertName(_ name: String, address: String) {
+        if toText.isFirstResponder {
             toText.delegate?.tokenField!(toText, didEnterText: name, mail: address)
             if LogHandler.logging {
-                LogHandler.doLog(UIViewResolver.resolve(toText.tag), interaction: "insert", point: CGPoint(x: 0, y: Int((toText.dataSource?.numberOfTokensInTokenField!(toText))!)), comment: name + " " + address)
+                LogHandler.doLog(UIViewResolver.resolve(toText.tag), interaction: "insert", point: CGPoint(x: 0, y: Int((toText.dataSource?.numberOfTokens!(in: toText))!)), comment: name + " " + address)
             }
-        } else if ccText.isFirstResponder() {
+        } else if ccText.isFirstResponder {
             ccText.delegate?.tokenField!(ccText, didEnterText: name, mail: address)
             if LogHandler.logging {
-                LogHandler.doLog(UIViewResolver.resolve(ccText.tag), interaction: "insert", point: CGPoint(x: 0, y: Int((ccText.dataSource?.numberOfTokensInTokenField!(ccText))!)), comment: name + " " + address)
+                LogHandler.doLog(UIViewResolver.resolve(ccText.tag), interaction: "insert", point: CGPoint(x: 0, y: Int((ccText.dataSource?.numberOfTokens!(in: ccText))!)), comment: name + " " + address)
             }
         }
     }
 
-    func searchContacts(prefix: String) {
+    func searchContacts(_ prefix: String) {
         AppDelegate.getAppDelegate().requestForAccess({ access in
             //print(access)
         })
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                let contacts = try AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName(prefix), keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName), CNContactEmailAddressesKey, CNContactImageDataKey, CNContactThumbnailImageDataKey])
+                let contacts = try AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: CNContact.predicateForContacts(matchingName: prefix), keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: CNContactFormatterStyle.fullName), CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor, CNContactThumbnailImageDataKey as CNKeyDescriptor])
                 tableDataDelegate.contacts = []
                 tableDataDelegate.addresses = []
                 tableDataDelegate.pictures = []
                 for c in contacts {
                     for mail in c.emailAddresses {
-                        if let name = CNContactFormatter.stringFromContact(c, style: .FullName) {
+                        if let name = CNContactFormatter.string(from: c, style: .fullName) {
                             self.tableDataDelegate.contacts.append(name)
                         } else {
                             self.tableDataDelegate.contacts.append(c.givenName + c.familyName)
                         }
-                        self.tableDataDelegate.addresses.append(mail.value as! String)
+                        self.tableDataDelegate.addresses.append(mail.value as String)
                         self.tableDataDelegate.pictures.append(c.getImageOrDefault())
                     }
                 }
@@ -451,10 +451,10 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         AppDelegate.getAppDelegate().requestForAccess({ access in
             print(access)
         })
-        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
-        if authorizationStatus == CNAuthorizationStatus.Authorized {
+        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
+        if authorizationStatus == CNAuthorizationStatus.authorized {
             do {
-                print(try AppDelegate.getAppDelegate().contactStore.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("o"), keysToFetch: [CNContactGivenNameKey]))
+                print(try AppDelegate.getAppDelegate().contactStore.unifiedContacts(matching: CNContact.predicateForContacts(matchingName: "o"), keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor]))
             }
             catch {
                 print("exception")
@@ -465,7 +465,7 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         }
     }
     
-    func newInput(tokenField: VENTokenField){
+    func newInput(_ tokenField: VENTokenField){
         print("input")
         animateIfNeeded()
 
@@ -488,56 +488,56 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         //reloadCollectionViews()
     }
 
-    func keyboardOpen(notification: NSNotification) {
+    func keyboardOpen(_ notification: Notification) {
         //if reducedSize == 0{
         LogHandler.doLog("keyboard", interaction: "open", point: CGPoint(x: 0, y: 0), comment: "")
         var info = notification.userInfo!
-        let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
+        let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
         reducedSize = keyboardFrame.size.height
 
         keyboardY = keyboardFrame.origin.y
         //print("keyboard ", keyboardY)
 
-        if toText.isFirstResponder() {
+        if toText.isFirstResponder {
             toCollectionview.reloadData()
-            UIView.animateWithDuration(2.5, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { self.toCollectionviewHeight.constant = 100 }, completion: nil)
+            UIView.animate(withDuration: 2.5, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { self.toCollectionviewHeight.constant = 100 }, completion: nil)
         }
-        if ccText.isFirstResponder() {
+        if ccText.isFirstResponder {
             ccCollectionviewHeight.constant = 100
             ccCollectionview.reloadData()
         }
-        if !toText.isFirstResponder() {
-            UIView.animateWithDuration(2.5, animations: { () -> Void in self.toCollectionviewHeight.constant = 0 })
+        if !toText.isFirstResponder {
+            UIView.animate(withDuration: 2.5, animations: { () -> Void in self.toCollectionviewHeight.constant = 0 })
         }
-        if !ccText.isFirstResponder() {
+        if !ccText.isFirstResponder {
             ccCollectionviewHeight.constant = 0
         }
 
-        UIView.animateWithDuration(0.1, animations: { () -> Void in
+        UIView.animate(withDuration: 0.1, animations: { () -> Void in
 
             let contentInsets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0.0, self.reducedSize, 0.0)
             self.scrollview!.contentInset = contentInsets
         })
     }
 
-    func keyboardClose(notification: NSNotification) {
+    func keyboardClose(_ notification: Notification) {
         LogHandler.doLog("keyboard", interaction: "close", point: CGPoint(x: 0, y: 0), comment: "")
         if reducedSize != 0 {
-            UIView.animateWithDuration(0.1, animations: { () -> Void in
+            UIView.animate(withDuration: 0.1, animations: { () -> Void in
                 self.reducedSize = 0
                 let contentInsets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0.0, self.reducedSize, 0.0)
                 self.scrollview!.contentInset = contentInsets
             })
-            if !toText.isFirstResponder() {
+            if !toText.isFirstResponder {
                 toCollectionviewHeight.constant = 0
             }
-            if !ccText.isFirstResponder() {
+            if !ccText.isFirstResponder {
                 ccCollectionviewHeight.constant = 0
             }
         }
     }
 
-    func iconButton(sender: AnyObject) {
+    func iconButton(_ sender: AnyObject) {
         //print(sender.absoluteString)
         //print(recognizer.locationOfTouch(recognizer.numberOfTouches()-1, inView: imageView))
         /*for var i in 1 ..< recognizer.numberOfTouches(){
@@ -547,45 +547,45 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         let alert: UIAlertController
         let url: String
         if !m {
-            alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "Postcard label"), message: NSLocalizedString("SendInsecureInfo", comment: "Postcard infotext"), preferredStyle: .Alert)
+            alert = UIAlertController(title: NSLocalizedString("Postcard", comment: "Postcard label"), message: NSLocalizedString("SendInsecureInfo", comment: "Postcard infotext"), preferredStyle: .alert)
             url = "https://enzevalos.org/infos/postcard"
         } else {
-            alert = UIAlertController(title: NSLocalizedString("Letter", comment: "Letter label"), message: NSLocalizedString("SendSecureInfo", comment: "Letter infotext"), preferredStyle: .Alert)
+            alert = UIAlertController(title: NSLocalizedString("Letter", comment: "Letter label"), message: NSLocalizedString("SendSecureInfo", comment: "Letter infotext"), preferredStyle: .alert)
             url = "https://enzevalos.org/infos/letter"
         }
-        alert.addAction(UIAlertAction(title: NSLocalizedString("MoreInformation", comment: "More Information label"), style: .Default, handler: { (action: UIAlertAction!) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: url)!) }))
-        alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
-        dispatch_async(dispatch_get_main_queue(), {
-            self.presentViewController(alert, animated: true, completion: nil)
+        alert.addAction(UIAlertAction(title: NSLocalizedString("MoreInformation", comment: "More Information label"), style: .default, handler: { (action: UIAlertAction!) -> Void in UIApplication.shared.openURL(URL(string: url)!) }))
+        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
+        DispatchQueue.main.async(execute: {
+            self.present(alert, animated: true, completion: nil)
         })
     }
 
-    @IBAction func pressCancel(sender: AnyObject) {
+    @IBAction func pressCancel(_ sender: AnyObject) {
         var alert: UIAlertController
         var firstResponder: UIView?
-        for view in [toText, ccText, subjectText, textView] {
-            if view.isFirstResponder() {
+        for view in [toText, ccText, subjectText, textView] as [UIView] {
+            if view.isFirstResponder {
                 firstResponder = view
             }
         }
         if textView.text == "" && toText.mailTokens.count == 0 && ccText.mailTokens.count == 0 && subjectText.inputText() == "" {
-            self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
+            self.navigationController?.dismiss(animated: true, completion: nil)
         } else {
-            alert = UIAlertController(title: NSLocalizedString("discard", comment: "discard"), message: NSLocalizedString("discardText", comment: ""), preferredStyle: .Alert)
-            alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "cancel"), style: .Cancel, handler: { (action: UIAlertAction!) -> Void in
+            alert = UIAlertController(title: NSLocalizedString("discard", comment: "discard"), message: NSLocalizedString("discardText", comment: ""), preferredStyle: .alert)
+            alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "cancel"), style: .cancel, handler: { (action: UIAlertAction!) -> Void in
                 firstResponder?.becomeFirstResponder()
             }))
-            alert.addAction(UIAlertAction(title: NSLocalizedString("discardButton", comment: "discard"), style: .Destructive, handler: { (action: UIAlertAction!) -> Void in
-                self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
+            alert.addAction(UIAlertAction(title: NSLocalizedString("discardButton", comment: "discard"), style: .destructive, handler: { (action: UIAlertAction!) -> Void in
+                self.navigationController?.dismiss(animated: true, completion: nil)
             }))
-            dispatch_async(dispatch_get_main_queue(), {
+            DispatchQueue.main.async(execute: {
                 self.view.endEditing(true)
-                self.presentViewController(alert, animated: true, completion: nil)
+                self.present(alert, animated: true, completion: nil)
             })
         }
     }
 
-    @IBAction func pressSend(sender: AnyObject) {
+    @IBAction func pressSend(_ sender: AnyObject) {
         let toEntrys = toText.mailTokens
         let ccEntrys = ccText.mailTokens
         let subject = subjectText.inputText()!
@@ -594,14 +594,14 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
         mailHandler.send(toEntrys as NSArray as! [String], ccEntrys: ccEntrys as NSArray as! [String], bccEntrys: [], subject: subject, message: message, callback: self.mailSend)
     }
 
-    func mailSend(error: NSError?) {
+    func mailSend(_ error: NSError?) {
         if (error != nil) {
             NSLog("Error sending email: \(error)")
             AppDelegate.getAppDelegate().showMessage("An error occured", completion: nil)
         } else {
             NSLog("Send successful!")
             if (self.answerTo != nil) {
-                AppDelegate.getAppDelegate().mailHandler.addFlag((self.answerTo?.uid)!, flags: MCOMessageFlag.Answered)
+                AppDelegate.getAppDelegate().mailHandler.addFlag((self.answerTo?.uid)!, flags: MCOMessageFlag.answered)
             }
             //AppDelegate.getAppDelegate().showMessage("Send successfully", completion: self.sendCompleted)
             self.sendCompleted()
@@ -609,7 +609,7 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
     }
 
     func sendCompleted() {
-        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
+        self.navigationController?.dismiss(animated: true, completion: nil)
     }
 
     func getContemporarySecurityState() -> Bool {
@@ -647,15 +647,15 @@ class SendViewController: UIViewController, UITextViewDelegate, UIGestureRecogni
             if(ThemeManager.animation()) {
                 setAnimation()
                 if contemporarySecureState {
-                    UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
+                    UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
                         self.navigationController?.navigationBar.barTintColor = ThemeManager.encryptedMessageColor()
                     }, completion: nil)
                 } else {
-                    UIView.animateWithDuration(0.5, delay: 0, options: [UIViewAnimationOptions.CurveEaseIn/*, UIViewAnimationOptions.Autoreverse*/], animations: {
+                    UIView.animate(withDuration: 0.5, delay: 0, options: [UIViewAnimationOptions.curveEaseIn/*, UIViewAnimationOptions.Autoreverse*/], animations: {
                         self.navigationController?.navigationBar.barTintColor = ThemeManager.uncryptedMessageColor()
                     }, completion: { (_: Bool) in
                         sleep(1)
-                        UIView.animateWithDuration(0.5, delay: 1.5, options: UIViewAnimationOptions.CurveEaseIn, animations: {
+                        UIView.animate(withDuration: 0.5, delay: 1.5, options: UIViewAnimationOptions.curveEaseIn, animations: {
                             self.navigationController?.navigationBar.barTintColor = ThemeManager.uncryptedMessageColor()
                         }, completion: nil)
                     })
diff --git a/enzevalos_iphone/State+CoreDataClass.swift b/enzevalos_iphone/State+CoreDataClass.swift
index 3201f9b49772eabf58a5b11293447a222f511f67..cfe2f941c23a6a8efe1781417b668505d6490fa5 100644
--- a/enzevalos_iphone/State+CoreDataClass.swift
+++ b/enzevalos_iphone/State+CoreDataClass.swift
@@ -10,6 +10,6 @@ import Foundation
 import CoreData
 
 @objc(State)
-public class State: NSManagedObject {
+open class State: NSManagedObject {
     
 }
diff --git a/enzevalos_iphone/State+CoreDataProperties.swift b/enzevalos_iphone/State+CoreDataProperties.swift
index 6be0999ab0edf208ff4c94e22362a0efaf71edb5..1ce6c39f5254a0c516709993db5ecfbbd4ddb10e 100644
--- a/enzevalos_iphone/State+CoreDataProperties.swift
+++ b/enzevalos_iphone/State+CoreDataProperties.swift
@@ -12,22 +12,22 @@ import CoreData
 
 extension State {
 
-    @nonobjc public override class func fetchRequest() -> NSFetchRequest {
+    @nonobjc public override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
         return NSFetchRequest(entityName: "State");
     }
 
     public var currentMails: Int{
         set {
             let name = "currentMails"
-            self.willChangeValueForKey(name)
+            self.willChangeValue(forKey: name)
             self.setPrimitiveValue(newValue, forKey: name)
-            self.didChangeValueForKey(name)
+            self.didChangeValue(forKey: name)
         }
         get {
             let name = "currentMails"
-            self.willAccessValueForKey(name)
-            let result = Int(self.primitiveValueForKey(name) as! Int64)
-            self.didAccessValueForKey(name)
+            self.willAccessValue(forKey: name)
+            let result = Int(self.primitiveValue(forKey: name) as! Int64)
+            self.didAccessValue(forKey: name)
             return result
         }
     }
@@ -35,15 +35,15 @@ extension State {
     public var currentContacts: Int{
         set {
             let name = "currentContacts"
-            self.willChangeValueForKey(name)
+            self.willChangeValue(forKey: name)
             self.setPrimitiveValue(newValue, forKey: name)
-            self.didChangeValueForKey(name)
+            self.didChangeValue(forKey: name)
         }
         get {
             let name = "currentContacts"
-            self.willAccessValueForKey(name)
-            let result = Int(self.primitiveValueForKey(name) as! Int64)
-            self.didAccessValueForKey(name)
+            self.willAccessValue(forKey: name)
+            let result = Int(self.primitiveValue(forKey: name) as! Int64)
+            self.didAccessValue(forKey: name)
             return result
         }
     }
@@ -51,15 +51,15 @@ extension State {
     public var maxUID: UInt64{
         set {
             let name = "maxUID"
-            self.willChangeValueForKey(name)
-            self.setPrimitiveValue(NSDecimalNumber(unsignedLongLong: newValue), forKey: name)
-            self.didChangeValueForKey(name)
+            self.willChangeValue(forKey: name)
+            self.setPrimitiveValue(NSDecimalNumber(value: newValue as UInt64), forKey: name)
+            self.didChangeValue(forKey: name)
         }
         get {
             let name = "maxUID"
-            self.willAccessValueForKey(name)
-            let result = (self.primitiveValueForKey(name) as! NSDecimalNumber).unsignedLongLongValue
-            self.didAccessValueForKey(name)
+            self.willAccessValue(forKey: name)
+            let result = (self.primitiveValue(forKey: name) as! NSDecimalNumber).uint64Value
+            self.didAccessValue(forKey: name)
             return result
         }
 
diff --git a/enzevalos_iphone/TableViewDataDelegate.swift b/enzevalos_iphone/TableViewDataDelegate.swift
index 5ce4c91bf896bd3de7669a759a324590c1174e47..85bacefc86bb9800f9984bad8d354decf0c61ec3 100644
--- a/enzevalos_iphone/TableViewDataDelegate.swift
+++ b/enzevalos_iphone/TableViewDataDelegate.swift
@@ -18,17 +18,17 @@ class TableViewDataDelegate : NSObject, UITableViewDelegate, UITableViewDataSour
     //weak var tokenField : VENTokenField?
     var insertCallback : (String, String) -> Void = {(name : String, address : String) -> Void in return}
     
-    init(insertCallback : (String, String) -> Void){
+    init(insertCallback : @escaping (String, String) -> Void){
         self.insertCallback = insertCallback
         super.init()
     }
     
-    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
+    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return contacts.count
     }
     
-    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
-        let cell = tableView.dequeueReusableCellWithIdentifier("contacts") as! ContactCell
+    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
+        let cell = tableView.dequeueReusableCell(withIdentifier: "contacts") as! ContactCell
         cell.name.text = contacts[indexPath.row]
         cell.address.text = addresses[indexPath.row]
         cell.img.layer.cornerRadius = cell.img.frame.height/2
@@ -40,18 +40,18 @@ class TableViewDataDelegate : NSObject, UITableViewDelegate, UITableViewDataSour
         
         if !EnzevalosEncryptionHandler.hasKey(cell.address.text!) {//!AddressHandler.proveAddress(cell.address.text!)){
             //cell.backgroundColor = UIColor.orangeColor()
-            cell.name.textColor! = UIColor.orangeColor()
-            cell.address.textColor! = UIColor.orangeColor()
+            cell.name.textColor! = UIColor.orange
+            cell.address.textColor! = UIColor.orange
         }
         else {
             //cell.backgroundColor = nil
-            cell.name.textColor! = UIColor.blackColor()
-            cell.address.textColor! = UIColor.blackColor()
+            cell.name.textColor! = UIColor.black
+            cell.address.textColor! = UIColor.black
         }
         return cell
     }
     
-    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
+    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         /*if (tokenField != nil) {
             tokenField?.delegate?.tokenField!(tokenField!, didEnterText: contacts[indexPath.row], mail: addresses[indexPath.row])
         }*/
diff --git a/enzevalos_iphone/TextFormatter.swift b/enzevalos_iphone/TextFormatter.swift
index d641fc088613c1d7f6da1a05e9948e436cb0982e..a638b3a5030c1f25e7d07b3a26aa4a0716481711 100644
--- a/enzevalos_iphone/TextFormatter.swift
+++ b/enzevalos_iphone/TextFormatter.swift
@@ -9,13 +9,13 @@
 import Foundation
 
 class TextFormatter {
-    static func insertBeforeEveryLine(insertion: String, text: String) -> String{
-        let textSep = text.componentsSeparatedByString("\n")
+    static func insertBeforeEveryLine(_ insertion: String, text: String) -> String{
+        let textSep = text.components(separatedBy: "\n")
         var ret = ""
         for t in textSep {
-            ret.appendContentsOf(insertion)
-            ret.appendContentsOf(t)
-            ret.appendContentsOf("\n")
+            ret.append(insertion)
+            ret.append(t)
+            ret.append("\n")
         }
         return ret
     }
diff --git a/enzevalos_iphone/Theme.swift b/enzevalos_iphone/Theme.swift
index ddff87d7e782e91ff396134253c09f667742240e..d8c94afb980b791b76d041ff99454ec0f433c05f 100644
--- a/enzevalos_iphone/Theme.swift
+++ b/enzevalos_iphone/Theme.swift
@@ -20,14 +20,14 @@ enum Theme: Int{
      Strong security indicators -> weak + different colors
      Very strong security indicators -> strong + animation
     */
-   case No_security_indicator, Weak_security_indicator, Strong_security_indicator, Very_strong_security_indicator
+   case no_security_indicator, weak_security_indicator, strong_security_indicator, very_strong_security_indicator
     
     
     var uncryptedMessageColor: UIColor{
         switch  self {
-        case .No_security_indicator:
+        case .no_security_indicator:
             return defaultColor
-        case .Weak_security_indicator:
+        case .weak_security_indicator:
                 return defaultColor
         default:
             // orange
@@ -39,9 +39,9 @@ enum Theme: Int{
     
     var encryptedMessageColor: UIColor{
         switch  self {
-        case .No_security_indicator:
+        case .no_security_indicator:
             return defaultColor
-        case .Weak_security_indicator:
+        case .weak_security_indicator:
             return defaultColor
         default:
             // green
@@ -52,9 +52,9 @@ enum Theme: Int{
     
     var encryptedVerifiedMessageColor: UIColor{
         switch  self {
-        case .No_security_indicator:
+        case .no_security_indicator:
             return defaultColor
-        case .Weak_security_indicator:
+        case .weak_security_indicator:
             return defaultColor
         default:
             // green
@@ -64,9 +64,9 @@ enum Theme: Int{
     
     var troubleMessageColor: UIColor{
         switch  self {
-        case .No_security_indicator:
+        case .no_security_indicator:
             return defaultColor
-        case .Weak_security_indicator:
+        case .weak_security_indicator:
             return defaultColor
         default:
             // red
@@ -80,10 +80,10 @@ enum Theme: Int{
 
 struct ThemeManager{
     static func currentTheme() -> Theme {
-        if let storedTheme = NSUserDefaults.standardUserDefaults().valueForKey(SelectedThemeKey)?.integerValue {
+        if let storedTheme = (UserDefaults.standard.value(forKey: SelectedThemeKey)? as AnyObject).intValue {
             return Theme(rawValue: storedTheme)!
         } else {
-            return .Very_strong_security_indicator
+            return .very_strong_security_indicator
         }
     }
     
@@ -104,12 +104,12 @@ struct ThemeManager{
     }
     
     static func animation() -> Bool {
-            return currentTheme() == .Very_strong_security_indicator
+            return currentTheme() == .very_strong_security_indicator
     }
     
-    static func applyTheme(theme: Theme) {
-        NSUserDefaults.standardUserDefaults().setValue(theme.rawValue, forKey: SelectedThemeKey)
-        NSUserDefaults.standardUserDefaults().synchronize()
+    static func applyTheme(_ theme: Theme) {
+        UserDefaults.standard.setValue(theme.rawValue, forKey: SelectedThemeKey)
+        UserDefaults.standard.synchronize()
     }
     
     static var defaultColor: UIColor = UIColor(red: 249/255, green: 249/255, blue: 249/255, alpha: 1.0)
diff --git a/enzevalos_iphone/UIViewResolver.swift b/enzevalos_iphone/UIViewResolver.swift
index ae340f1a93b6422dda94c5aa126c9f240ea1e28a..3c5a7aeb7885d4c6f75ba3035eb1fd24413420ec 100644
--- a/enzevalos_iphone/UIViewResolver.swift
+++ b/enzevalos_iphone/UIViewResolver.swift
@@ -11,9 +11,9 @@ import UIKit
 enum UIViewResolver : Int {
     case unknown=0, cancel, imageView, send, toText, toCollectionview, ccText, ccCollectionview, subjectText, textView, tableview, scrollview
     
-    internal static func resolve(tag : Int) -> String{
+    internal static func resolve(_ tag : Int) -> String{
         if let ui = UIViewResolver(rawValue: tag) {
-            return String(ui)
+            return String(describing: ui)
         }
         return ""
     }
diff --git a/enzevalos_iphone/UserData.swift b/enzevalos_iphone/UserData.swift
index 5542da8259804fcef721b1fe45df732eccbd8fba..ac6355c6774bfbb8c10e332724bf0815da45f9b3 100644
--- a/enzevalos_iphone/UserData.swift
+++ b/enzevalos_iphone/UserData.swift
@@ -11,60 +11,60 @@ import Foundation
 
 
 enum Attribute: Int{
-    case Accountname, UserName, UserAddr, UserPW, SMTPHostname, SMTPPort, IMAPHostname, IMAPPort, PrefEncryption, PublicKey, AutocryptType, IMAPConnectionType, IMAPAuthType, SMTPConnectionType, SMTPAuthType
+    case accountname, userName, userAddr, userPW, smtpHostname, smtpPort, imapHostname, imapPort, prefEncryption, publicKey, autocryptType, imapConnectionType, imapAuthType, smtpConnectionType, smtpAuthType
     
     var defaultValue:AnyObject? {
         switch self {
-        case .Accountname:
-            return Attribute.attributeValues[Attribute.Accountname]! //return "Alice"
-        case .UserName:
-            return Attribute.attributeValues[Attribute.UserName]! //return "Alice2005"
-        case .UserAddr:
-            return Attribute.attributeValues[Attribute.UserAddr]! //return "alice2005@web.de"
-        case .UserPW:
-            return Attribute.attributeValues[Attribute.UserPW]! //return "WJ$CE:EtUo3E$"
-        case .SMTPHostname:
-            return Attribute.attributeValues[Attribute.SMTPHostname]! //return "smtp.web.de"
-        case .SMTPPort:
-            return 587
-        case .IMAPHostname:
-            return "imap.web.de"
-        case .IMAPPort:
-            return 993
-        case .PrefEncryption:
-            return "yes" // yes or no
-        case .AutocryptType:
-            return "p" // only openpgp 
-        case .IMAPConnectionType:
-            return MCOConnectionType.TLS.rawValue
-        case .IMAPAuthType:
-            return MCOAuthType.SASLPlain.rawValue
-        case .SMTPConnectionType:
-            return MCOConnectionType.StartTLS.rawValue
-        case .SMTPAuthType:
-            return MCOAuthType.SASLPlain.rawValue
+        case .accountname:
+            return Attribute.attributeValues[Attribute.accountname]! //return "Alice"
+        case .userName:
+            return Attribute.attributeValues[Attribute.userName]! //return "Alice2005"
+        case .userAddr:
+            return Attribute.attributeValues[Attribute.userAddr]! //return "alice2005@web.de"
+        case .userPW:
+            return Attribute.attributeValues[Attribute.userPW]! //return "WJ$CE:EtUo3E$"
+        case .smtpHostname:
+            return Attribute.attributeValues[Attribute.smtpHostname]! //return "smtp.web.de"
+        case .smtpPort:
+            return 587 as AnyObject?
+        case .imapHostname:
+            return "imap.web.de" as AnyObject?
+        case .imapPort:
+            return 993 as AnyObject?
+        case .prefEncryption:
+            return "yes" as AnyObject? // yes or no
+        case .autocryptType:
+            return "p" as AnyObject? // only openpgp 
+        case .imapConnectionType:
+            return MCOConnectionType.TLS.rawValue as AnyObject?
+        case .imapAuthType:
+            return MCOAuthType.SASLPlain.rawValue as AnyObject?
+        case .smtpConnectionType:
+            return MCOConnectionType.StartTLS.rawValue as AnyObject?
+        case .smtpAuthType:
+            return MCOAuthType.SASLPlain.rawValue as AnyObject?
             
-        case .PublicKey:
-            return ""
+        case .publicKey:
+            return "" as AnyObject?
         }
     }
     
-    static let allAttributes = [Accountname, UserName, UserAddr, UserPW, SMTPHostname, SMTPPort, IMAPHostname, IMAPPort, PrefEncryption, PublicKey, AutocryptType]
-    static var attributeValues: [Attribute : AnyObject?] = [.Accountname : "Alice", .UserName : "Alice2005", .UserAddr : "alice2005@web.de", .UserPW : "WJ$CE:EtUo3E$", .SMTPHostname : "smtp.web.de", .SMTPPort : 587, .IMAPHostname : "imap.web.de", .IMAPPort : 993, .PrefEncryption : "yes", .AutocryptType : "p", .PublicKey : ""]
+    static let allAttributes = [accountname, userName, userAddr, userPW, smtpHostname, smtpPort, imapHostname, imapPort, prefEncryption, publicKey, autocryptType]
+    static var attributeValues: [Attribute : AnyObject?] = [.accountname : "Alice" as AnyObject?, .userName : "Alice2005" as Optional<AnyObject>, .userAddr : "alice2005@web.de" as Optional<AnyObject>, .userPW : "WJ$CE:EtUo3E$" as Optional<AnyObject>, .smtpHostname : "smtp.web.de" as Optional<AnyObject>, .smtpPort : 587 as Optional<AnyObject>, .imapHostname : "imap.web.de" as Optional<AnyObject>, .imapPort : 993, .prefEncryption : "yes", .autocryptType : "p", .publicKey : ""]
 }
 
 
 struct UserManager{
-    static func storeUserValue(value: AnyObject?, attribute: Attribute) -> Bool{
-        NSUserDefaults.standardUserDefaults().setValue(value, forKey: "\(attribute.hashValue)")
-        NSUserDefaults.standardUserDefaults().synchronize()
+    static func storeUserValue(_ value: AnyObject?, attribute: Attribute) -> Bool{
+        UserDefaults.standard.setValue(value, forKey: "\(attribute.hashValue)")
+        UserDefaults.standard.synchronize()
         return true
     }
     
-    static func loadUserValue(attribute: Attribute) -> AnyObject?{
-        let value = NSUserDefaults.standardUserDefaults().valueForKey("\(attribute.hashValue)")
+    static func loadUserValue(_ attribute: Attribute) -> AnyObject?{
+        let value = UserDefaults.standard.value(forKey: "\(attribute.hashValue)")
         if((value) != nil){
-            return value
+            return value as AnyObject?
         }
         else{
             storeUserValue(attribute.defaultValue, attribute: attribute)
@@ -75,7 +75,7 @@ struct UserManager{
     
     static func resetUserValues(){
         for a in Attribute.allAttributes {
-            NSUserDefaults.standardUserDefaults().removeObjectForKey("\(a.hashValue)")
+            UserDefaults.standard.removeObject(forKey: "\(a.hashValue)")
         }
     }
 }
diff --git a/enzevalos_iphone/VENDataDelegate.swift b/enzevalos_iphone/VENDataDelegate.swift
index 0592897d31aa3588b47d79f685e05ec46bef6e7e..b2158bb27b43e43718671425172c6e21b1c2aea2 100644
--- a/enzevalos_iphone/VENDataDelegate.swift
+++ b/enzevalos_iphone/VENDataDelegate.swift
@@ -10,15 +10,15 @@ import VENTokenField
 
 class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegate {
     
-    var changeFunc: (VENTokenField -> Void) = {(_ : VENTokenField) -> Void in
+    var changeFunc: ((VENTokenField) -> Void) = {(_ : VENTokenField) -> Void in
         //print ("hallo")
     }
     
-    var beginFunc: (VENTokenField -> Void) = {(_ : VENTokenField) -> Void in }
+    var beginFunc: ((VENTokenField) -> Void) = {(_ : VENTokenField) -> Void in }
     
     var deleteFunc: (() -> Void) = {() -> Void in }
     
-    var tappedWhenSelectedFunc: (String -> Void)? = nil
+    var tappedWhenSelectedFunc: ((String) -> Void)? = nil
     
     //Used to show enzevalos-Contacts
     //Have a look at tokenField(... didTappedTokenTwice ...)
@@ -28,7 +28,7 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
         super.init()
     }
     
-    init(changeFunc: (VENTokenField -> Void), tappedWhenSelectedFunc: (String -> Void)?/*, beginFunc: (VENTokenField -> Void)*/, deleteFunc: (() -> Void)){
+    init(changeFunc: @escaping ((VENTokenField) -> Void), tappedWhenSelectedFunc: ((String) -> Void)?/*, beginFunc: (VENTokenField -> Void)*/, deleteFunc: @escaping (() -> Void)){
         self.changeFunc = changeFunc
         self.tappedWhenSelectedFunc = tappedWhenSelectedFunc
         self.deleteFunc = deleteFunc
@@ -36,56 +36,56 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
         super.init()
     }
     
-    func tokenField(tokenField: VENTokenField, didChangeText text: String?) {
+    func tokenField(_ tokenField: VENTokenField, didChangeText text: String?) {
         changeFunc(tokenField)
     }
    
-    func tokenField(tokenField: VENTokenField, colorSchemeForTokenAtIndex index: UInt) -> UIColor {
+    func tokenField(_ tokenField: VENTokenField, colorSchemeForTokenAt index: UInt) -> UIColor {
         if EnzevalosEncryptionHandler.hasKey(tokenField.mailTokens[Int(index)] as! String) {
             return UIColor.init(red: 0, green: 122.0/255.0, blue: 1, alpha: 1)
         }
-        return UIColor.orangeColor()
+        return UIColor.orange
     }
     
-    func tokenFieldDidBeginEditing(tokenField: VENTokenField) {
+    func tokenFieldDidBeginEditing(_ tokenField: VENTokenField) {
         //print("begin")
         //print(numberOfTokensInTokenField(tokenField))
         beginFunc(tokenField)
     }
     
-    func tokenField(tokenField: VENTokenField, didEnterText text: String) {
-        tokenField.textTokens.addObject(text.lowercaseString)
+    func tokenField(_ tokenField: VENTokenField, didEnterText text: String) {
+        tokenField.textTokens.add(text.lowercased())
         if AddressHandler.inContacts(text) {
             //TODO Mailadresse aus Kontakt holen
         }
         else {
-            tokenField.mailTokens.addObject(text)
+            tokenField.mailTokens.add(text)
         }
         tokenField.reloadData()
         changeFunc(tokenField)
-        tokenField.sendActionsForControlEvents(UIControlEvents.EditingDidEnd)
+        tokenField.sendActions(for: UIControlEvents.editingDidEnd)
     }
     
-    func tokenField(tokenField: VENTokenField, didEnterText text: String, mail email: String) {
-        tokenField.textTokens.addObject(text)
-        tokenField.mailTokens.addObject(email)
+    func tokenField(_ tokenField: VENTokenField, didEnterText text: String, mail email: String) {
+        tokenField.textTokens.add(text)
+        tokenField.mailTokens.add(email)
         tokenField.reloadData()
         changeFunc(tokenField)
-        tokenField.sendActionsForControlEvents(UIControlEvents.EditingDidEnd)
+        tokenField.sendActions(for: UIControlEvents.editingDidEnd)
     }
     
-    func tokenField(tokenField: VENTokenField, didDeleteTokenAtIndex index: UInt) {
+    func tokenField(_ tokenField: VENTokenField, didDeleteTokenAt index: UInt) {
         if LogHandler.logging {
             LogHandler.doLog(UIViewResolver.resolve(tokenField.tag), interaction: "delete", point: CGPoint(x: Int(index), y: 0), comment: (tokenField.textTokens[Int(index)] as! String)+" "+(tokenField.mailTokens[Int(index)] as! String))
         }
-        tokenField.textTokens.removeObjectAtIndex(Int(index))
-        tokenField.mailTokens.removeObjectAtIndex(Int(index))
+        tokenField.textTokens.removeObject(at: Int(index))
+        tokenField.mailTokens.removeObject(at: Int(index))
         tokenField.reloadData()
         deleteFunc()
-        tokenField.sendActionsForControlEvents(UIControlEvents.EditingDidEnd)
+        tokenField.sendActions(for: UIControlEvents.editingDidEnd)
     }
     
-    func tokenField(tokenField: VENTokenField, titleForTokenAtIndex index: UInt) -> String {
+    func tokenField(_ tokenField: VENTokenField, titleForTokenAt index: UInt) -> String {
         return tokenField.textTokens[Int(index)] as! String
     }
     
@@ -93,13 +93,13 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
         return UInt((tokenField.textTokens.count))
     }
     
-    func tokenFieldCollapsedText(tokenField: VENTokenField) -> String {
+    func tokenFieldCollapsedText(_ tokenField: VENTokenField) -> String {
         var text : String = "names: "
         text.appendContentsOf(String(tokenField.dataSource?.numberOfTokensInTokenField!(tokenField)))
         return text
     }
     
-    func tokenField(tokenField: VENTokenField, didChangeContentHeight height: CGFloat) {
+    func tokenField(_ tokenField: VENTokenField, didChangeContentHeight height: CGFloat) {
         //print("height: ",height)
         for c in tokenField.constraints {
             if (c.identifier == "tokenFieldHeight"){
@@ -111,10 +111,10 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
     
     //eigene Methoden
     
-    func tokenFieldDidEndEditing(tokenF: VENTokenField){
+    func tokenFieldDidEndEditing(_ tokenF: VENTokenField){
         //print("end")
         if let last = tokenF.inputText() {
-            if last.stringByReplacingOccurrencesOfString(" ", withString: "") != "" {
+            if last.replacingOccurrences(of: " ", with: "") != "" {
                 tokenField(tokenF, didEnterText: last)
             }
         }
@@ -124,7 +124,7 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
         return tokenField.textTokens
     }*/
     
-    func isSecure(tokenField: VENTokenField) -> Bool {
+    func isSecure(_ tokenField: VENTokenField) -> Bool {
         var secure = true
         for entry in tokenField.mailTokens{
             secure = secure && EnzevalosEncryptionHandler.hasKey(entry as! String) //KeyHandler.getHandler().addrHasKey(entry as! String)//AddressHandler.proveAddress(entry as! NSString)
@@ -132,7 +132,7 @@ class VENDataDelegate : NSObject, VENTokenFieldDataSource , VENTokenFieldDelegat
         return secure
     }
     
-    func tokenField(tokenField: VENTokenField, didTappedTokenTwice index: UInt){
+    func tokenField(_ tokenField: VENTokenField, didTappedTokenTwice index: UInt){
         if let fun = tappedWhenSelectedFunc {
             fun(tokenField.mailTokens[Int(index)] as! String)
         }
diff --git a/enzevalos_iphone/enzevalos_iphone-Bridging-Header.h b/enzevalos_iphone/enzevalos_iphone-Bridging-Header.h
index e8464d1359e0a434c67c68722ea1aa72cedc4a9f..d8b25ed0e190b22523f4673bfc2e8bf8adbd6da5 100644
--- a/enzevalos_iphone/enzevalos_iphone-Bridging-Header.h
+++ b/enzevalos_iphone/enzevalos_iphone-Bridging-Header.h
@@ -7,7 +7,7 @@
 //
 
 #import <MailCore/MailCore.h>
-#import <BZipCompression/BZipCompression.h>
+//#import <BZipCompression/BZipCompression.h>
 #import <Onboard/OnboardingViewController.h>
 #import <Onboard/OnboardingContentViewController.h>
 #import "ObjectivePGP.h"
diff --git a/enzevalos_iphoneTests/enzevalos_iphoneTests.swift b/enzevalos_iphoneTests/enzevalos_iphoneTests.swift
index ce9e6a9a37380e49858f3f3232a8479e99b2bae5..2e8cecd908ea9a8bf94c649783c802c97d709971 100644
--- a/enzevalos_iphoneTests/enzevalos_iphoneTests.swift
+++ b/enzevalos_iphoneTests/enzevalos_iphoneTests.swift
@@ -28,18 +28,18 @@ class enzevalos_iphoneTests: XCTestCase {
     
     func testPerformanceExample() {
         // This is an example of a performance test case.
-        self.measureBlock {
+        self.measure {
             // Put the code you want to measure the time of here.
         }
     }
     
     
-    func isSorted(array: [KeyRecord]) -> Bool {
+    func isSorted(_ array: [KeyRecord]) -> Bool {
         let startIndex = 0
         let endIndex = array.count - 1
         
         var previousIndex = startIndex
-        var currentIndex = startIndex.successor()
+        var currentIndex = (startIndex + 1)
         
         while currentIndex < endIndex {
             
@@ -48,7 +48,7 @@ class enzevalos_iphoneTests: XCTestCase {
             }
             
             previousIndex = currentIndex
-            currentIndex = currentIndex.successor()
+            currentIndex = (currentIndex + 1)
         }
         
         return true