repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
honghaoz/UW-Quest-iOS | UW Quest/Model/PersonalInformations.swift | 1 | 29583 | //
// PersonalInformations.swift
// UW Quest
//
// Created by Honghao on 9/21/14.
// Copyright (c) 2014 Honghao. All rights reserved.
//
import Foundation
enum PersonalInformationType: String {
case Addresses = "Addresses"
case Names = "Names"
case PhoneNumbers = "Phone Numbers"
case EmailAddresses = "Email Addresses"
case EmergencyContacts = "Emergency Contacts"
case DemographicInformation = "Demographic Information"
case CitizenshipImmigrationDocuments = "Citizenship/Immigration Documents"
static let allValues = [Addresses.rawValue, Names.rawValue, PhoneNumbers.rawValue, EmailAddresses.rawValue, EmergencyContacts.rawValue, DemographicInformation.rawValue, CitizenshipImmigrationDocuments.rawValue]
}
class PersonalInformation {
let categories: [String]!
var addresses: [Address]!
var names: [Name]!
var namesMessage: String?
var phoneNumbers: [PhoneNumber]!
var phoneNumbersMessage: String?
var emailAddresses: EmailAddress?
var emailAddressesMessage: String?
var emergencyContacts: [EmergencyContact]!
var emergencyContactsMessage: String?
var demograhicInformation: DemographicInformation?
var demograhicInformationMessage: String?
var citizenshipImmigrationDocument: CitizenshipImmigrationDocument?
var citizenshipImmigrationDocumentMessage: String?
init() {
logInfo("PersonalInformation inited")
categories = PersonalInformationType.allValues
addresses = []
names = []
phoneNumbers = []
emergencyContacts = []
}
class Address {
// Keys
class var kAddress: String {return "Address"}
class var kAddressType: String {return "Address Type"}
class func newAddress(rawDict: Dictionary<String, String>) -> Address? {
if let address: String = rawDict[Address.kAddress] {
if let addressType: String = rawDict[Address.kAddressType] {
return Address(address: address, type: addressType)
}
}
return nil
}
var address: String
var type: String
init(address: String, type: String) {
self.address = address
self.type = type
}
}
/**
Use raw data from json to init addresses
:param: rawData data object from json, either array or dictionary
:returns: true if successfully inited
*/
func initAddresses(rawData: AnyObject) -> Bool {
// Passed in a dictionary
if let dataDict = rawData as? Dictionary<String, String> {
if let newAddress: Address = Address.newAddress(dataDict) {
self.addresses = [newAddress]
return true
}
return false
}
// Passed in an array of dictionary
if let dataArray = rawData as? [Dictionary<String, String>] {
var tempAddresses = [Address]()
for eachDataDict in dataArray {
if let newAddress: Address = Address.newAddress(eachDataDict) {
tempAddresses.append(newAddress)
} else {
// Some error happens
self.addresses = []
return false
}
}
// If goes here, no error happens
self.addresses = tempAddresses
return true
}
// Invalid type
return false
}
class Name {
var name: String
var nameType: String
class var kName: String {return "Name"}
class var kNameType: String {return "Name Type"}
class func newName(rawDict: Dictionary<String, String>) -> Name? {
let name: String? = rawDict[Name.kName]
let nameType: String? = rawDict[Name.kNameType]
if (name != nil) && (nameType != nil) {
return Name(name: name!, nameType: nameType!)
}
return nil
}
init(name: String, nameType: String) {
self.name = name
self.nameType = nameType
}
}
func initNames(rawData: AnyObject, message: String? = nil) -> Bool {
self.namesMessage = message
// Passed in a dictionary
if let dataDict = rawData as? Dictionary<String, String> {
if let newName: Name = Name.newName(dataDict) {
self.names = [newName]
return true
}
return false
}
// Passed in an array of dictionary
if let dataArray = rawData as? [Dictionary<String, String>] {
var tempNames = [Name]()
for eachDataDict in dataArray {
if let newName: Name = Name.newName(eachDataDict) {
tempNames.append(newName)
} else {
// Some error happens
self.names = []
return false
}
}
// If goes here, no error happens
self.names = tempNames
return true
}
// Invalid type
return false
}
class PhoneNumber {
var type: String
var country: String
var ext: String
var isPreferred: Bool
var telephone: String
class var kPhoneType: String {return "*Phone Type"}
class var kCountry: String {return "Country"}
class var kExtension: String {return "Ext"}
class var kPreferred: String {return "Preferred"}
class var kTelephone: String {return "*Telephone"}
class func newPhoneNumber(rawDict: Dictionary<String, String>) -> PhoneNumber? {
let phoneType: String? = rawDict[PhoneNumber.kPhoneType]
let country: String? = rawDict[PhoneNumber.kCountry]
let ext: String? = rawDict[PhoneNumber.kExtension]
let preferredString: String? = rawDict[PhoneNumber.kPreferred]
let preferred: Bool = preferredString == "Y" ? true : false
let telephone: String? = rawDict[PhoneNumber.kTelephone]
if (phoneType != nil) && (country != nil) && (ext != nil) && (preferredString != nil) && (telephone != nil) {
return PhoneNumber(type: phoneType!, country: country!, ext: ext!, isPreferred: preferred, telephone: telephone!)
}
return nil
}
init (type: String, country: String, ext: String, isPreferred: Bool, telephone: String) {
self.type = type
self.country = country
self.ext = ext
self.isPreferred = isPreferred
self.telephone = telephone
}
}
func initPhoneNumbers(rawData: AnyObject, message: String? = nil) -> Bool {
self.phoneNumbersMessage = message
// Passed in a dictionary
if let dataDict = rawData as? Dictionary<String, String> {
if let newPhoneNumber: PhoneNumber = PhoneNumber.newPhoneNumber(dataDict) {
self.phoneNumbers = [newPhoneNumber]
return true
}
return false
}
// Passed in an array of dictionary
if let dataArray = rawData as? [Dictionary<String, String>] {
var tempPhoneNumber = [PhoneNumber]()
for eachDataDict in dataArray {
if let newPhoneNumber: PhoneNumber = PhoneNumber.newPhoneNumber(eachDataDict) {
tempPhoneNumber.append(newPhoneNumber)
} else {
// Some error happens
self.phoneNumbers = []
return false
}
}
// If goes here, no error happens
self.phoneNumbers = tempPhoneNumber
return true
}
// Invalid type
return false
}
class EmailAddress {
// Alternate email address
class Email {
var type: String
var address: String
class var kType: String {return "Email Type"}
class var kAddress: String {return "Email Address"}
class func newEmail(rawDict: Dictionary<String, String>) -> Email? {
let type: String? = rawDict[kType]
let address: String? = rawDict[kAddress]
if (type != nil) && (address != nil) {
return Email(type: type!, address: address!)
}
return nil
}
init(type: String, address: String) {
self.type = type
self.address = address
}
}
class CampusEmail {
var campusEmail: String
var deliveredTo: String
class var kCampusEmail: String {return "Campus email"}
class var kDeliveredTo: String {return "Delivered to"}
class func newCampusEmail(rawDict: Dictionary<String, String>) -> CampusEmail? {
let campusEmail: String? = rawDict[kCampusEmail]
let deliveredTo: String? = rawDict[kDeliveredTo]
if (campusEmail != nil) && (deliveredTo != nil) {
return CampusEmail(campusEmail: campusEmail!, deliveredTo: deliveredTo!)
}
return nil
}
init(campusEmail: String, deliveredTo: String) {
self.campusEmail = campusEmail
self.deliveredTo = deliveredTo
}
}
var alternateEmailAddress: [Email]!
var alternateEmailDescription: String?
var campusEmailAddress: CampusEmail!
var campusEmailDescription: String?
var description: String?
init(description: String?, alternateEmails: [Email], alternateEmailDescription: String?, campusEmail: CampusEmail, campusEmailDescription: String?) {
self.description = description
self.alternateEmailAddress = alternateEmails
self.alternateEmailDescription = alternateEmailDescription
self.campusEmailAddress = campusEmail
self.campusEmailDescription = campusEmailDescription
}
}
func initEmailAddresses(rawData: AnyObject, message: String? = nil) -> Bool {
self.emailAddressesMessage = message
if let dataDict = rawData as? Dictionary<String, AnyObject> {
let description: String? = dataDict["description"] as AnyObject? as? String
let alternateEmailAddressDict: Dictionary<String, AnyObject>? = dataDict["alternate_email_address"] as AnyObject? as? Dictionary<String, AnyObject>
let campusEmailAddressDict: Dictionary<String, AnyObject>? = dataDict["campus_email_address"] as AnyObject? as? Dictionary<String, AnyObject>
if (campusEmailAddressDict != nil) {
let alternateEmailDescription: String? = alternateEmailAddressDict?["description"] as AnyObject? as? String
let alternateEmailData: [Dictionary<String, String>]? = alternateEmailAddressDict?["data"] as AnyObject? as? [Dictionary<String, String>]
let campusEmailDescription: String? = campusEmailAddressDict!["description"] as AnyObject? as? String
let campusEmailData: [Dictionary<String, String>]? = campusEmailAddressDict!["data"] as AnyObject? as? [Dictionary<String, String>]
if (campusEmailData != nil) {
var tempAlternateEmails: [EmailAddress.Email] = []
if (alternateEmailData != nil) {
for eachAlternateEmail in alternateEmailData! {
if let newEmail = EmailAddress.Email.newEmail(eachAlternateEmail) {
tempAlternateEmails.append(newEmail)
} else {
// Some error happens
return false
}
}
}
let campusEmail: EmailAddress.CampusEmail? = EmailAddress.CampusEmail.newCampusEmail(campusEmailData![0])
if (campusEmail != nil) {
// Successfully
self.emailAddresses = EmailAddress(description: description, alternateEmails: tempAlternateEmails, alternateEmailDescription: alternateEmailDescription, campusEmail: campusEmail!, campusEmailDescription: campusEmailDescription)
return true
}
}
}
}
return false
}
class EmergencyContact {
var contactName: String
var country: String
var ext: String
var phone: String
var isPrimary: Bool
var relationship: String
class var kContactName: String {return "Contact Name"}
class var kCountry: String {return "Country"}
class var kExtension: String {return "Extension"}
class var kPhone: String {return "Phone"}
class var kPrimary: String {return "Primary Contact"}
class var kRelationship: String {return "Relationship"}
class func newContact(rawDict: Dictionary<String, String>) -> EmergencyContact? {
let contactName: String? = rawDict[EmergencyContact.kContactName]
let country: String? = rawDict[EmergencyContact.kCountry]
let ext: String? = rawDict[EmergencyContact.kExtension]
let phone: String? = rawDict[EmergencyContact.kPhone]
let primaryString: String? = rawDict[EmergencyContact.kPrimary]
let isPrimary: Bool = primaryString == "Y" ? true : false
let relationship: String? = rawDict[EmergencyContact.kRelationship]
if (contactName != nil) && (country != nil) && (ext != nil) && (phone != nil) && (primaryString != nil) && (relationship != nil) {
return EmergencyContact(contactName: contactName!, country: country!, ext: ext!, phone: phone!, isPrimary: isPrimary, relationship: relationship!)
}
return nil
}
init (contactName: String, country: String, ext: String, phone: String, isPrimary: Bool, relationship: String) {
self.contactName = contactName
self.country = country
self.ext = ext
self.phone = phone
self.isPrimary = isPrimary
self.relationship = relationship
}
}
func initEmergencyContacts(rawData: AnyObject, message: String? = nil) -> Bool {
self.emergencyContactsMessage = message
// Passed in a dictionary
if let dataDict = rawData as? Dictionary<String, String> {
if let newContact: EmergencyContact = EmergencyContact.newContact(dataDict) {
self.emergencyContacts = [newContact]
return true
}
return false
}
// Passed in an array of dictionary
if let dataArray = rawData as? [Dictionary<String, String>] {
var tempContancts = [EmergencyContact]()
for eachDataDict in dataArray {
if let newContact: EmergencyContact = EmergencyContact.newContact(eachDataDict) {
tempContancts.append(newContact)
} else {
// Some error happens
self.emergencyContacts = []
return false
}
}
// If goes here, no error happens
self.emergencyContacts = tempContancts
return true
}
// Invalid type
return false
}
// class DemographicInformation {
//
// class CitizenshipInformation {
// var country: String
// var description: String
//
// class var kCountry: String {return "country"}
// class var kDescription: String {return "description"}
//
// class func newCitizenshipInformations(rawData: [Dictionary<String, String>]) -> [CitizenshipInformation]? {
// var tempList: [CitizenshipInformation] = []
// for eachDict in rawData {
// let country: String? = eachDict[CitizenshipInformation.kCountry]
// let description: String? = eachDict[CitizenshipInformation.kDescription]
// if (country != nil) && (description != nil) {
// tempList.append(CitizenshipInformation(country: country!, description: description!))
// } else {
// return nil
// }
// }
// return tempList
// }
//
// init(country: String, description: String) {
// self.country = country
// self.description = description
// }
// }
// var citizenshipInformations: [CitizenshipInformation]?
//
// class Demographic {
// var dateOfBirth: String
// var gender: String
// var id: String
// var maritalStatus: String
//
// class var kDateOfBirth: String {return "date_of_birth"}
// class var kGender: String {return "gender"}
// class var kId: String {return "id"}
// class var kMaritalStatus: String {return "marital_status"}
//
// class func newDemographic(rawDict: Dictionary<String, String>) -> Demographic? {
// let dateOfBirth: String? = rawDict[Demographic.kDateOfBirth]
// let gender: String? = rawDict[Demographic.kGender]
// let id: String? = rawDict[Demographic.kId]
// let maritalStatus: String? = rawDict[Demographic.kMaritalStatus]
//
// if (dateOfBirth != nil) && (gender != nil) && (id != nil) && (maritalStatus != nil) {
// return Demographic(dateOfBirth: dateOfBirth!, gender: gender!, id: id!, maritalStatus: maritalStatus!)
// } else {
// return nil
// }
// }
//
// init(dateOfBirth: String, gender: String, id: String, maritalStatus: String) {
// self.dateOfBirth = dateOfBirth
// self.gender = gender
// self.id = id
// self.maritalStatus = maritalStatus
// }
// }
//
// var demographicInfo: Demographic?
//
// class NationalIdentificationNumber {
// var country: String
// var nationalId: String
// var nationalIdType: String
//
// class var kCountry: String {return "country"}
// class var kNationalId: String {return "national_id"}
// class var kNationalIdType: String {return "national_id_type"}
//
// class func newNationalIds(rawData: [Dictionary<String, String>]) -> [NationalIdentificationNumber]? {
// var tempList: [NationalIdentificationNumber] = []
// for eachDict in rawData {
// let country: String? = eachDict[NationalIdentificationNumber.kCountry]
// let nationalId: String? = eachDict[NationalIdentificationNumber.kNationalId]
// let nationalIdType: String? = eachDict[NationalIdentificationNumber.kNationalIdType]
// if (country != nil) && (nationalId != nil) && (nationalIdType != nil) {
// tempList.append(NationalIdentificationNumber(country: country!, nationalId: nationalId!, nationalIdType: nationalIdType!))
// } else {
// return nil
// }
// }
// return tempList
// }
//
// init(country: String, nationalId: String, nationalIdType: String) {
// self.country = country
// self.nationalId = nationalId
// self.nationalIdType = nationalIdType
// }
// }
//
// var nationalIdNumbers: [NationalIdentificationNumber]?
// var note: String?
//
// class VisaOrPermitData {
// var country: String
// var type: String
//
// class var kCountry: String {return "country"}
// class var kType: String {return "type"}
//
// class func newVisa(rawDict: Dictionary<String, String>) -> VisaOrPermitData? {
// let country: String? = rawDict[VisaOrPermitData.kCountry]
// let type: String? = rawDict[VisaOrPermitData.kType]
// if (country != nil) && (type != nil) {
// return VisaOrPermitData(country: country!, type: type!)
// } else {
// return nil
// }
// }
//
// init(country: String, type: String) {
// self.country = country
// self.type = type
// }
// }
// var visaOrPermitData: VisaOrPermitData?
// }
// func initDemographicInformation(rawData: AnyObject, message: String? = nil) -> Bool {
// self.demograhicInformationMessage = message
// let citizenshipsData: [Dictionary<String, String>]? = rawData["citizenship_information"] as AnyObject? as? [Dictionary<String, String>]
// let demographicData: Dictionary<String, String>? = rawData["demographic_information"] as AnyObject? as? Dictionary<String, String>
// let nationalIdsData: [Dictionary<String, String>]? = rawData["national_identification_number"] as AnyObject? as? [Dictionary<String, String>]
// let note: String? = rawData["note"] as AnyObject? as? String
// let visaData: Dictionary<String, String>? = rawData["visa_or_permit_data"] as AnyObject? as? Dictionary<String, String>
// if (citizenshipsData != nil) && (demographicData != nil) && (nationalIdsData != nil) && (visaData != nil) {
// self.demograhicInformation = DemographicInformation()
//
// if let citizenshipInfos: [DemographicInformation.CitizenshipInformation] = DemographicInformation.CitizenshipInformation.newCitizenshipInformations(citizenshipsData!) {
// self.demograhicInformation!.citizenshipInformations = citizenshipInfos
// } else {
// return false
// }
//
// if let demographicInfo: DemographicInformation.Demographic = DemographicInformation.Demographic.newDemographic(demographicData!) {
// self.demograhicInformation!.demographicInfo = demographicInfo
// } else {
// return false
// }
//
// if let nationalIdNumbers: [DemographicInformation.NationalIdentificationNumber] = DemographicInformation.NationalIdentificationNumber.newNationalIds(nationalIdsData!) {
// self.demograhicInformation!.nationalIdNumbers = nationalIdNumbers
// } else {
// return false
// }
//
// self.demograhicInformation!.note = note
//
// if let visaOrPermitData: DemographicInformation.VisaOrPermitData = DemographicInformation.VisaOrPermitData.newVisa(visaData!) {
// self.demograhicInformation!.visaOrPermitData = visaOrPermitData
// } else {
//// return false
// }
// return true
// }
// return false
// }
class DemographicInformation {
var keys = ["Demographic Information", "National Identification Number", "Ethnicity", "Citizenship Information", "Driver's License", "Visa or Permit Data"]
var dictionary = Dictionary<String, [[String]]>()
var message = "If any of the information above is wrong, contact your administrative office."
}
func initDemographicInformation(rawData: AnyObject, message: String? = nil) -> Bool {
self.demograhicInformationMessage = message
if var dict: Dictionary<String, AnyObject> = rawData as? Dictionary<String, AnyObject> {
self.demograhicInformation = DemographicInformation()
if dict.has("Message") {
demograhicInformation!.message = dict["Message"] as! String
dict.removeValueForKey("Message")
}
// self.demograhicInformation!.keys = Array(dict.keys)
self.demograhicInformation!.dictionary = dict as! Dictionary<String, [[String]]>
return true
} else {
return false
}
}
// class CitizenshipImmigrationDocument {
// class visaDocument {
// var country: String
// var dateReceived: String?
// var expirationDate: String?
// var visaType: String
//
// class var kCountry: String {return "country"}
// class var kDateReceived: String {return "date_received"}
// class var kExpirationDate: String {return "expiration_date"}
// class var kVisaType: String {return "visa_type"}
//
// class func newDocument(rawDict: Dictionary<String, String>) -> visaDocument? {
// let country: String? = rawDict[visaDocument.kCountry]
// let dateReceived: String? = rawDict[visaDocument.kDateReceived]
// let expirationDate: String? = rawDict[visaDocument.kExpirationDate]
// let visaType: String? = rawDict[visaDocument.kVisaType]
// if (country != nil) && (visaType != nil) {
// return visaDocument(country: country!, dateReceived: dateReceived, expirationDate: expirationDate, visaType: visaType!)
// } else {
// return nil
// }
// }
//
// init (country: String, dateReceived: String?, expirationDate: String?, visaType: String) {
// self.country = country
// self.dateReceived = dateReceived
// self.expirationDate = expirationDate
// self.visaType = visaType
// }
// }
// var requiredDocumentation: [visaDocument]!
// var pastDocumentation: [visaDocument]!
// init() {
// self.requiredDocumentation = []
// self.pastDocumentation = []
// }
// }
//
// func initCitizenshipImmigrationDocument(rawData: AnyObject, message: String? = nil) -> Bool {
// self.citizenshipImmigrationDocumentMessage = message
// println(self.citizenshipImmigrationDocumentMessage)
// let pastDocList: [Dictionary<String, String>]? = rawData["past_documentation"] as AnyObject? as? [Dictionary<String, String>]
// println(pastDocList)
// let requiredDocList: [Dictionary<String, String>]? = rawData["required_documentation"] as AnyObject? as? [Dictionary<String, String>]
// println(requiredDocList)
// if (requiredDocList == nil) && (pastDocList == nil) && (self.citizenshipImmigrationDocumentMessage != nil) {
// println("should here")
// return true
// }
// self.citizenshipImmigrationDocument = CitizenshipImmigrationDocument()
// if requiredDocList != nil {
// var tempDocList: [CitizenshipImmigrationDocument.visaDocument] = []
// for eachDoc in requiredDocList! {
// var newDoc: CitizenshipImmigrationDocument.visaDocument? = CitizenshipImmigrationDocument.visaDocument.newDocument(eachDoc)
// if newDoc != nil {
// tempDocList.append(newDoc!)
// } else {
// return false
// }
// }
// self.citizenshipImmigrationDocument!.requiredDocumentation = tempDocList
// } else {
// return false
// }
//
// if pastDocList != nil {
// var tempDocList: [CitizenshipImmigrationDocument.visaDocument] = []
// for eachDoc in pastDocList! {
// var newDoc: CitizenshipImmigrationDocument.visaDocument? = CitizenshipImmigrationDocument.visaDocument.newDocument(eachDoc)
// if newDoc != nil {
// tempDocList.append(newDoc!)
// } else {
// return false
// }
// }
// self.citizenshipImmigrationDocument!.pastDocumentation = tempDocList
// }
// return true
// }
class CitizenshipImmigrationDocument {
var docs: [Dictionary<String, AnyObject>]
init(rawData: [Dictionary<String, AnyObject>]) {
docs = rawData
}
}
func initCitizenshipImmigrationDocument(rawData: AnyObject, message: String? = nil) -> Bool {
if let docList: [Dictionary<String, AnyObject>] = rawData as? [Dictionary<String, AnyObject>] {
citizenshipImmigrationDocument = CitizenshipImmigrationDocument(rawData: docList)
return true
} else {
return false
}
}
} | apache-2.0 | 85657986a79d963ab55e208f50618c3f | 42.314788 | 251 | 0.565392 | 4.800876 | false | false | false | false |
Pargi/Pargi-iOS | Pargi/Data/UserData.swift | 1 | 7291 | //
// UserData.swift
// Pargi
//
// Storing user preferences/data, while also
// giving access to legacy data from old Pargi versions
//
// Created by Henri Normak on 01/06/2017.
// Copyright © 2017 Henri Normak. All rights reserved.
//
import Foundation
import CoreLocation
import Cereal
struct UserData {
// Notification, fired when a change is made to the shared user data
// object of the notification is the (now updated) shared user data
static let UpdatedNotification = Notification.Name("UserDataUpdatedNotification")
// User info key for the UpdatedNotification containing the previous UserData value
static let OldUserDataKey = "OldUserDataKey"
var deviceIdentifier: String
var licensePlateNumber: String?
var otherLicensePlateNumbers: [String]
var isParked: Bool = false
var parkedAt: Date? = nil
var currentParkedZone: Zone? = nil
var currentUnsuitableAlternativeZones: [Zone]? = nil
var currentParkedCoordinate: CLLocationCoordinate2D? = nil
private static let userDataURL: URL = {
let base = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
return base.appendingPathComponent("user")
}()
static var shared: UserData = {
let url = UserData.userDataURL
do {
let data = try Data(contentsOf: url)
let value: UserData = try CerealDecoder.rootCerealItem(with: data)
return value
} catch {
// Swallow the error, fall back to legacy user data
// or if not present to a default set
// Keys are from old code (i.e legacy)
let userDefaults = UserDefaults.standard
let license = userDefaults.string(forKey: "Car Number") ?? userDefaults.string(forKey: "PargiCurrentCar")
let otherLicenses: [String] = userDefaults.array(forKey: "Recent plates") as? [String] ?? []
let isParked = userDefaults.bool(forKey: "isParked")
let parkedAt = userDefaults.value(forKey: "PargiStartDate") as? Date
let parkedZone: Zone? = {
if let parkedZoneCode = userDefaults.string(forKey: "PargiCurrentZone") {
return ApplicationData.currentDatabase.zone(forCode: parkedZoneCode)
}
return nil
}()
// Generate a new UUID for the device (just a random UUID)
let identifier = UUID().uuidString
return UserData(deviceIdentifier: identifier, licensePlateNumber: license, otherLicensePlateNumbers: otherLicenses, isParked: isParked, parkedAt: parkedAt, currentParkedZone: parkedZone, currentUnsuitableAlternativeZones: nil, currentParkedCoordinate: nil)
}
}() {
didSet {
// Sync back to disk
self.queue.async {
if let data = try? CerealEncoder.data(withRoot: self.shared) {
try? data.write(to: self.userDataURL)
}
}
// Fire off a notification
NotificationCenter.default.post(name: UserData.UpdatedNotification, object: self.shared, userInfo: [UserData.OldUserDataKey: oldValue])
}
}
// Convenience
mutating func startParking(withZone zone: Zone, unsuitableAlternatives: [Zone]? = nil, andCoordinate coordinate: CLLocationCoordinate2D? = nil) {
self.isParked = true
self.currentParkedZone = zone
self.currentUnsuitableAlternativeZones = unsuitableAlternatives
self.currentParkedCoordinate = coordinate
self.parkedAt = Date()
}
mutating func endParking() {
self.isParked = false
self.currentParkedZone = nil
self.currentUnsuitableAlternativeZones = nil
self.currentParkedCoordinate = nil
self.parkedAt = nil
}
// MARK: Background write
private static let queue: DispatchQueue = DispatchQueue(label: "UserData.Sync")
}
extension UserData: CerealType {
private enum Keys {
static let deviceIdentifier = "deviceIdentifier"
static let licensePlateNumber = "licensePlateNumber"
static let otherLicensePlateNumbers = "otherLicensePlateNumbers"
static let isParked = "isParked"
static let parkedAt = "parkedAt"
static let currentParkedZone = "currentParkedZone"
static let currentParkedCoordinate = "currentParkedCoordinate"
static let currentUnsuitableAlternativeZones = "currentUnsuitableAlternativeZones"
}
init(decoder: Cereal.CerealDecoder) throws {
let deviceIdentifier: String = try decoder.decode(key: Keys.deviceIdentifier) ?? UUID().uuidString
let license: String? = try decoder.decode(key: Keys.licensePlateNumber)
let otherLicenses: [String] = try decoder.decode(key: Keys.otherLicensePlateNumbers) ?? []
let isParked: Bool = try decoder.decode(key: Keys.isParked)!
let parkedAt: Date? = try decoder.decode(key: Keys.parkedAt)
let currentParkedZone: Zone? = try decoder.decodeCereal(key: Keys.currentParkedZone)
let currentParkedCoordinate: CLLocationCoordinate2D? = try decoder.decodeCereal(key: Keys.currentParkedCoordinate)
let currentUnsuitableAlternativeZones: [Zone]? = try decoder.decodeCereal(key: Keys.currentUnsuitableAlternativeZones)
self.init(deviceIdentifier: deviceIdentifier, licensePlateNumber: license, otherLicensePlateNumbers: otherLicenses, isParked: isParked, parkedAt: parkedAt, currentParkedZone: currentParkedZone, currentUnsuitableAlternativeZones: currentUnsuitableAlternativeZones, currentParkedCoordinate: currentParkedCoordinate)
}
func encodeWithCereal(_ encoder: inout Cereal.CerealEncoder) throws {
try encoder.encode(self.deviceIdentifier, forKey: Keys.deviceIdentifier)
try encoder.encode(self.licensePlateNumber, forKey: Keys.licensePlateNumber)
try encoder.encode(self.otherLicensePlateNumbers, forKey: Keys.otherLicensePlateNumbers)
try encoder.encode(self.isParked, forKey: Keys.isParked)
try encoder.encode(self.parkedAt, forKey: Keys.parkedAt)
try encoder.encode(self.currentParkedZone, forKey: Keys.currentParkedZone)
try encoder.encode(self.currentParkedCoordinate, forKey: Keys.currentParkedCoordinate)
try encoder.encode(self.currentUnsuitableAlternativeZones, forKey: Keys.currentUnsuitableAlternativeZones)
}
}
// Add Cereal support to CLLocationCoordinate2D
extension CLLocationCoordinate2D: CerealType {
private struct Keys {
static let latitude = "latitude"
static let longitude = "longitude"
}
public init(decoder: CerealDecoder) throws {
let latitude: CLLocationDegrees = try decoder.decode(key: Keys.latitude)!
let longitude: CLLocationDegrees = try decoder.decode(key: Keys.longitude)!
self.init(latitude: latitude, longitude: longitude)
}
public func encodeWithCereal(_ encoder: inout CerealEncoder) throws {
try encoder.encode(self.latitude, forKey: Keys.latitude)
try encoder.encode(self.longitude, forKey: Keys.longitude)
}
}
| mit | f4c8bd9b0fe89dbbe82a5e8d69a09562 | 44.5625 | 321 | 0.686968 | 4.611006 | false | false | false | false |
migueloruiz/la-gas-app-swift | lasgasmx/DataBucket.swift | 1 | 2043 | //
// DataBucket.swift
// lasgasmx
//
// Created by Desarrollo on 4/4/17.
// Copyright © 2017 migueloruiz. All rights reserved.
//
import Foundation
protocol ConnectBucketDelegate: class {
func makeConnection(resource: Request, completion: @escaping (Result<Data, Error>) -> Void)
}
class DataBucket {
internal let session: URLSession
internal let baseURL: URL
init(baseURL: URL, session: URLSession = URLSession(configuration: URLSessionConfiguration.default)) {
self.baseURL = baseURL
self.session = session
}
}
extension DataBucket: ConnectBucketDelegate {
internal func makeConnection(resource: Request, completion: @escaping (Result<Data, Error>) -> Void) {
let request = resource.toRequest(baseURL: baseURL)
session.dataTask(with: request) { (data, response, error) in
guard let d = data else {
completion(.Failure(.Network(error!.localizedDescription)))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.Failure(.Status("No Response")))
return
}
guard httpResponse.statusCode < 400 else {
completion(.Failure(.Status("Error statusCode: \(httpResponse.statusCode)")))
return
}
completion(.Success(d))
}.resume()
}
}
protocol ConnectLocalBucketDelegate: class {
func makeConnection(completion: @escaping (Result<Data, Error>) -> Void)
}
class LocalDataBucket {
internal let fileName: String
init(fileName: String) {
self.fileName = fileName
}
}
extension LocalDataBucket: ConnectLocalBucketDelegate {
func makeConnection(completion: @escaping (Result<Data, Error>) -> Void) {
let path = Bundle.main.path(forResource: fileName, ofType: "json")
let data = NSData(contentsOfFile: path!)!
completion(.Success(data as Data))
}
}
| mit | 19d8ca6bc5d8f3bf571ccce80532d462 | 29.029412 | 106 | 0.622429 | 4.683486 | false | false | false | false |
ziaukhan/Swift-Big-Nerd-Ranch-Guide | chapter 4/Hypnosister/Hypnosister/HypnosisView.swift | 1 | 1537 | //
// HypnosisView.swift
// Hypnosister
//
import UIKit
class HypnosisView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
// Initialization code
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// Drawing code
let bounds = self.bounds
let center = CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.width / 2)
let maxRadius = (min(bounds.size.width, bounds.size.height) / 2.0)
var path = UIBezierPath()
//path.addArcWithCenter(center, radius, 0.0, (M_PI * 2), true)
for(var currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20){
path.moveToPoint(CGPointMake(center.x + currentRadius, center.y))
path.addArcWithCenter(center, radius: currentRadius, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
}
path.lineWidth = 10
UIColor.lightGrayColor().setStroke()
path.stroke()
var img = UIImage(named: "logo.png")
img.drawInRect(bounds)
//var text = "By Zia Khan"
//text.drawInRect(bounds, withAttributes: Dictionary())
}
}
| apache-2.0 | c75cde055fa5d86e32729f1630dc6561 | 31.702128 | 129 | 0.625244 | 4.098667 | false | false | false | false |
openHPI/xikolo-ios | iOS/Data/Model/CourseItem+DragItem.swift | 1 | 874 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
extension CourseItem {
func dragItem(with previewView: UIView?) -> UIDragItem {
let itemProvider = NSItemProvider(object: self)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = self
// Use default preview if no preview view was passed
dragItem.previewProvider = previewView.flatMap { view -> (() -> UIDragPreview?) in
return { () -> UIDragPreview? in
let parameters = UIDragPreviewParameters()
parameters.visiblePath = UIBezierPath(roundedRect: view.bounds, cornerRadius: CALayer.CornerStyle.default.rawValue)
return UIDragPreview(view: view, parameters: parameters)
}
}
return dragItem
}
}
| gpl-3.0 | e032f58ae946cc08f977eb0a62b01d66 | 31.333333 | 131 | 0.646048 | 4.904494 | false | false | false | false |
carabina/ActionSwift3 | ActionSwift3/Global.swift | 1 | 818 | //
// Global.swift
// ActionSwiftSK
//
// Created by Craig on 6/05/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import UIKit
public func ==(lhs: DisplayObject, rhs: DisplayObject) -> Bool {
return lhs == rhs
}
public func trace(parms:String ...) {
println(parms)
}
public func trace(parms:Int) {
println(parms)
}
public func trace(parms:CGFloat) {
println(parms)
}
public func trace(parms:UInt) {
println(parms)
}
public func trace(parms:Double) {
println(parms)
}
///The return of AS3 data types
public typealias Boolean = Bool
//Trying to keep this codebase agnostic, regardless of some weird idiosyncronacies of the original datatypes, such as AS3 `int` not following correct case conventions!
public typealias int = Int
public typealias Number = CGFloat
| mit | 1dea13b04cbd8d434984eaa0eeacdadf | 22.371429 | 167 | 0.716381 | 3.436975 | false | false | false | false |
carabina/ActionSwift3 | ActionSwift3/display/DisplayObjectContainer.swift | 1 | 4285 | //
// DisplayObjectContainer.swift
// ActionSwiftSK
//
// Created by Craig on 5/05/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import UIKit
/**
A DisplayObjectContainer can contain DisplayObjects, using `addChild`, `addChildAt`, `getChildAt`, `removeChildAt`, etc.
*/
public class DisplayObjectContainer: InteractiveObject {
internal var children:[DisplayObject] = []
public var numChildren:UInt = 0
public func addChild(child:DisplayObject)->DisplayObject {
if let parent = child.node.parent {
child.node.removeFromParent()
}
child.stage = self.stage
self.node.addChild(child.node)
children.push(child)
child.parent = self
numChildren++
child.dispatchEvent(Event(.Added))
return(child)
}
public func addChildAt(child:DisplayObject,_ index:UInt)->DisplayObject {
return(addChildAt(child, index, dispatch:true))
}
private func addChildAt(child:DisplayObject,_ index:UInt, dispatch:Bool)->DisplayObject {
if let parent = child.node.parent {
child.node.removeFromParent()
}
self.node.insertChild(child.node, atIndex: Int(index))
children.splice(index, deleteCount: 0, values: child)
child.parent = self
numChildren++
if (dispatch) {
child.dispatchEvent(Event(.Added))
}
return(child)
}
public func contains(child:DisplayObject)->Bool {
return (getChildIndex(child) > -1)
}
public func getChildAt(index:UInt)->DisplayObject? {
return(children.get(Int(index)))
}
public func getChildByName(name:String)->DisplayObject? {
for child in children {
if (child.name==name) {
return child
}
}
return nil
}
public func getChildIndex(child:DisplayObject)->Int {
var index:Int = -1
for (var i:Int=0;i<Int(self.numChildren);i++) {
let t = self.getChildAt(UInt(i))
if (t === child) {
index = i
}
}
return(index)
}
public func removeChild(child:DisplayObject)->DisplayObject {
let index = getChildIndex(child)
if index > -1 {
self.node.removeChildrenInArray([child.node])
children.removeAtIndex(index)
}
child.parent = nil
child.dispatchEvent(Event(.Removed))
return (child)
}
public func removeChildAt(index:UInt)->DisplayObject? {
return(removeChildAt(index, dispatch: true))
}
private func removeChildAt(index:UInt, dispatch:Bool)->DisplayObject? {
if let child = children.get(Int(index)) {
self.node.removeChildrenInArray([child.node])
children.removeAtIndex(Int(index))
child.parent = nil
if (dispatch) {
child.dispatchEvent(Event(.Removed))
}
return (child)
}
return nil
}
public func removeChildren(beginIndex:UInt=0,_ endIndex:UInt = UInt.max) {
for (var i=beginIndex;i<endIndex;i++) {
removeChildAt(i)
}
}
public func setChildIndex(child:DisplayObject,_ index:UInt) {
addChildAt(child, index, dispatch:false)
}
public func swapChildren(child1:DisplayObject,child2:DisplayObject) {
var child1Index = getChildIndex(child1)
var child2Index = getChildIndex(child2)
if (child1Index > -1 && child2Index > -1) {
swapChildrenAt(UInt(child1Index), UInt(child2Index))
}
}
public func swapChildrenAt(index1:UInt,_ index2:UInt) {
if (index1>index2) {
var child1 = removeChildAt(index1, dispatch: false)
var child2 = removeChildAt(index2, dispatch: false)
if let child1 = child1 {
addChildAt(child1, index1, dispatch: false)
}
if let child2 = child2 {
addChildAt(child2, index2, dispatch: false)
}
}
}
override internal func update(currentTime:CFTimeInterval) {
super.update(currentTime)
for child in children {
child.update(currentTime)
}
}
}
| mit | 666c99fa548be414033653f5b6a1114c | 31.961538 | 120 | 0.595099 | 4.21752 | false | false | false | false |
linweiqiang/WQDouShi | WQDouShi/WQDouShi/Extesion/Category(扩展)/UIViewController+Extension.swift | 1 | 10219 | //
// UIViewController+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/11/30.
// Copyright © 2016年 i-Techsys. All rights reserved.
//
import UIKit
import MBProgressHUD
import SnapKit
private let mainScreenW = UIScreen.main.bounds.size.width
private let mainScreenH = UIScreen.main.bounds.size.height
// MARK: - HUD
extension UIViewController {
// MARK:- RuntimeKey 动态绑属性
// 改进写法【推荐】
struct RuntimeKey {
static let mg_HUDKey = UnsafeRawPointer.init(bitPattern: "mg_HUDKey".hashValue)
static let mg_GIFKey = UnsafeRawPointer(bitPattern: "mg_GIFKey".hashValue)
static let mg_GIFWebView = UnsafeRawPointer(bitPattern: "mg_GIFWebView".hashValue)
/// ...其他Key声明
}
// MARK:- HUD
/** ================================= HUD蒙版提示 ====================================== **/
// 蒙版提示HUD
var MBHUD: MBProgressHUD? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey) as? MBProgressHUD
}
}
/**
* 提示信息
*
* @param view 显示在哪个view
* @param hint 提示
*/
func showHudInView(view: UIView, hint: String?, yOffset: Float = 0.0) {
guard let hud = MBProgressHUD(view: view) else { return }
hud.labelText = hint
view.addSubview(hud)
if yOffset != 0.0 {
hud.margin = 10.0;
hud.yOffset += yOffset;
}
hud.show(true)
self.MBHUD = hud
}
/// 如果设置了图片名,mode的其他其他设置将失效
func showHudInViewWithMode(view: UIView, hint: String?, mode: MBProgressHUDMode = .text, imageName: String?) {
guard let hud = MBProgressHUD(view: view) else { return }
hud.labelText = hint
view.addSubview(hud)
hud.mode = mode
if imageName != nil {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: imageName!))
}
hud.show(true)
self.MBHUD = hud
}
/**
* 隐藏HUD
*/
func hideHud(){
self.MBHUD?.hide(true)
}
/**
* 提示信息 mode: MBProgressHUDModeText
*
* @param hint 提示
*/
func showHint(hint: String?, mode: MBProgressHUDMode = .text) {
//显示提示信息
guard let view = UIApplication.shared.delegate?.window else { return }
guard let hud = MBProgressHUD.showAdded(to: view, animated: true) else { return }
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.labelText = hint;
hud.mode = mode
hud.margin = 10.0;
hud.removeFromSuperViewOnHide = true
hud.hide(true, afterDelay: 2)
}
func showHint(hint: String?,mode: MBProgressHUDMode? = .text,view: UIView? = (UIApplication.shared.delegate?.window!)!, yOffset: Float = 0.0){
//显示提示信息
guard let hud = MBProgressHUD.showAdded(to: view, animated: true) else { return }
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.labelText = hint
if mode == .customView {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: "happy_face_icon"))
}
if mode != nil {
hud.mode = mode!
}
hud.margin = 15.0
if yOffset != 0.0 {
hud.yOffset += yOffset;
}
hud.removeFromSuperViewOnHide = true
hud.hide(true, afterDelay: 2)
}
// 带图片的提示HUD,延时2秒消失
func showHint(hint: String?,imageName: String?) {
guard let hud = MBProgressHUD.showAdded(to: view, animated: true) else { return }
hud.isUserInteractionEnabled = false
hud.mode = MBProgressHUDMode.text
hud.labelText = hint
if imageName != nil {
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named: imageName!))
}else {
hud.mode = .text
}
hud.removeFromSuperViewOnHide = true
hud.hide(true, afterDelay: 2)
}
// MARK: - 显示Gif图片
/** ============================ UIImageView显示GIF加载动画 =============================== **/
// MARK: - UIImageView显示Gif加载状态
/** 显示加载动画的UIImageView */
var mg_gifView: UIImageView? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey) as? UIImageView
}
}
/**
* 显示GIF加载动画
*
* @param images gif图片数组, 不传的话默认是自带的
* @param view 显示在哪个view上, 如果不传默认就是self.view
*/
func mg_showGifLoding(_ images: [UIImage]?,size: CGSize? , inView view: UIView?) {
var images = images
if images == nil {
images = [UIImage(named: "hold1_60x72")!,UIImage(named: "hold2_60x72")!,UIImage(named: "hold3_60x72")!]
}
var size = size
if size == nil {
size = CGSize(width: 60, height: 70)
}
let gifView = UIImageView()
var view = view
if view == nil {
view = self.view
}
view?.addSubview(gifView)
self.mg_gifView = gifView
gifView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(size!)
}
gifView.playGifAnimation(images: images!)
}
/**
* 取消GIF加载动画
*/
func mg_hideGifLoding() {
self.mg_gifView?.stopGifAnimation()
self.mg_gifView = nil;
}
/**
* 判断数组是否为空
*
* @param array 数组
*
* @return yes or no
*/
func isNotEmptyArray(array: [Any]) -> Bool {
if array.count >= 0 && !array.isEmpty{
return true
}else {
return false
}
}
/** ============================== UIWebView显示GIF加载动画 ================================= **/
// MARK: - UIWebView显示GIF加载动画
/** UIWebView显示Gif加载状态 */
weak var mg_GIFWebView: UIWebView? {
set {
objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView) as? UIWebView
}
}
/// 使用webView加载GIF图片
/**
* 如果view传了参数,移除的时候也要传同一个参数
*/
func mg_showWebGifLoading(frame:CGRect?, gifName: String?,view: UIView?, filter: Bool? = false) {
var gifName = gifName
if gifName == nil || gifName == "" {
gifName = "gif2"
}
var frame = frame
if frame == CGRect.zero || frame == nil {
frame = CGRect(x: 0, y: (self.navigationController != nil) ? MGNavHeight : CGFloat(0), width: mainScreenW, height: mainScreenH)
}
/// 得先提前创建webView,不能在子线程创建webView,不然程序会崩溃
let webView = UIWebView(frame: frame!)
// 子线程加载耗时操作加载GIF图片
DispatchQueue.global().async {
// 守卫校验
guard let filePath = Bundle.main.path(forResource: gifName, ofType: "gif") else {
return
}
guard let gifData: Data = NSData(contentsOfFile: filePath) as? Data else { return }
if (frame?.size.height)! < mainScreenH - MGNavHeight {
webView.center = CGPoint(x: (mainScreenW-webView.frame.size.width)/2, y: (mainScreenH-webView.frame.size.height)/2)
}else {
webView.center = self.view.center
}
webView.scalesPageToFit = true
webView.load(gifData, mimeType: "image/gif", textEncodingName: "UTF-8", baseURL: URL(fileURLWithPath: filePath))
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
webView.backgroundColor = UIColor.black
webView.isOpaque = false
webView.isUserInteractionEnabled = false
webView.tag = 10000
// 回到主线程将webView加到 UIApplication.shared.delegate?.window
DispatchQueue.main.async {
var view = view
if view == nil { // 添加到窗口
view = (UIApplication.shared.delegate?.window)!
}else { // 添加到控制器
self.mg_GIFWebView = webView
}
view?.addSubview(webView)
view?.bringSubview(toFront: webView)
//创建一个灰色的蒙版,提升效果( 可选 )
if filter! { // true
let filter = UIView(frame: self.view.frame)
filter.backgroundColor = UIColor(white: 0.9, alpha: 0.3)
webView.insertSubview(filter, at: 0)
}
}
}
}
/**
* 取消GIF加载动画,隐藏webView
*/
func mg_hideWebGifLoding(view: UIView?) {
if view == nil { // 从窗口中移除
guard let view = UIApplication.shared.delegate?.window else { return }
guard let webView = view?.viewWithTag(10000) as? UIWebView else { return }
webView.removeFromSuperview()
webView.alpha = 0.0
}else { // 从控制器中移除
self.mg_GIFWebView?.removeFromSuperview()
self.mg_GIFWebView?.alpha = 0.0
}
}
}
| mit | 9b36c3fcd6c94f52013238f31a83ec48 | 31.147157 | 149 | 0.548793 | 4.363141 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | TruckMuncher/api/RSearch.swift | 1 | 750 | //
// RTruck.swift
// TruckMuncher
//
// Created by Josh Ault on 10/27/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RSearch: RLMObject {
dynamic var blurb = ""
dynamic var truck = RTruck()
dynamic var menu = RMenu()
override init() {
super.init()
}
class func initFromProto(searchResponse: [String: AnyObject]) -> RSearch {
let rsearch = RSearch()
rsearch.blurb = searchResponse["blurb"] as? String ?? ""
rsearch.truck = RTruck.initFromProto(searchResponse["truck"] as! [String: AnyObject], isNew: false)
rsearch.menu = RMenu.initFromProto(searchResponse["menu"] as! [String: AnyObject])
return rsearch
}
}
| gpl-2.0 | 2b6f41cf3c7d15fc1160570299d388f6 | 25.785714 | 107 | 0.637333 | 3.75 | false | false | false | false |
chatspry/rubygens | Pods/Nimble/Nimble/Matchers/RaisesException.swift | 42 | 6146 | import Foundation
/// A Nimble matcher that succeeds when the actual expression raises an
/// exception with the specified name, reason, and/or userInfo.
///
/// Alternatively, you can pass a closure to do any arbitrary custom matching
/// to the raised exception. The closure only gets called when an exception
/// is raised.
///
/// nil arguments indicates that the matcher should not attempt to match against
/// that parameter.
public func raiseException(
named named: String? = nil,
reason: String? = nil,
userInfo: NSDictionary? = nil,
closure: ((NSException) -> Void)? = nil) -> MatcherFunc<Any> {
return MatcherFunc { actualExpression, failureMessage in
var exception: NSException?
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
actualExpression.evaluate()
return
}
setFailureMessageForException(failureMessage, exception: exception, named: named, reason: reason, userInfo: userInfo, closure: closure)
return exceptionMatchesNonNilFieldsOrClosure(exception, named: named, reason: reason, userInfo: userInfo, closure: closure)
}
}
internal func setFailureMessageForException(
failureMessage: FailureMessage,
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) {
failureMessage.postfixMessage = "raise exception"
if let named = named {
failureMessage.postfixMessage += " with name <\(named)>"
}
if let reason = reason {
failureMessage.postfixMessage += " with reason <\(reason)>"
}
if let userInfo = userInfo {
failureMessage.postfixMessage += " with userInfo <\(userInfo)>"
}
if let _ = closure {
failureMessage.postfixMessage += " that satisfies block"
}
if named == nil && reason == nil && userInfo == nil && closure == nil {
failureMessage.postfixMessage = "raise any exception"
}
if let exception = exception {
failureMessage.actualValue = "\(NSStringFromClass(exception.dynamicType)) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }"
} else {
failureMessage.actualValue = "no exception"
}
}
internal func exceptionMatchesNonNilFieldsOrClosure(
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) -> Bool {
var matches = false
if let exception = exception {
matches = true
if named != nil && exception.name != named {
matches = false
}
if reason != nil && exception.reason != reason {
matches = false
}
if userInfo != nil && exception.userInfo != userInfo {
matches = false
}
if let closure = closure {
let assertions = gatherFailingExpectations {
closure(exception)
}
let messages = assertions.map { $0.message }
if messages.count > 0 {
matches = false
}
}
}
return matches
}
@objc public class NMBObjCRaiseExceptionMatcher : NMBMatcher {
internal var _name: String?
internal var _reason: String?
internal var _userInfo: NSDictionary?
internal var _block: ((NSException) -> Void)?
internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) {
_name = name
_reason = reason
_userInfo = userInfo
_block = block
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
return raiseException(
named: _name,
reason: _reason,
userInfo: _userInfo,
closure: _block
).matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return !matches(actualBlock, failureMessage: failureMessage, location: location)
}
public var named: (name: String) -> NMBObjCRaiseExceptionMatcher {
return ({ name in
return NMBObjCRaiseExceptionMatcher(
name: name,
reason: self._reason,
userInfo: self._userInfo,
block: self._block
)
})
}
public var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher {
return ({ reason in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: reason,
userInfo: self._userInfo,
block: self._block
)
})
}
public var userInfo: (userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher {
return ({ userInfo in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: userInfo,
block: self._block
)
})
}
public var satisfyingBlock: (block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher {
return ({ block in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: self._userInfo,
block: block
)
})
}
}
extension NMBObjCMatcher {
public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil)
}
}
| mit | 5876e0d3c506f9e6540683abf361764e | 33.52809 | 197 | 0.582493 | 5.467972 | false | false | false | false |
EngrAhsanAli/AAFragmentManager | AAFragmentManager/Classes/AAFragmentManager.swift | 1 | 8153 | //
// AAFragmentManager.swift
// AAFragmentManager
//
// Created by Engr. Ahsan Ali on 01/04/2017.
// Copyright (c) 2017 AA-Creations. All rights reserved.
//
import UIKit
import ObjectiveC
open class AAFragmentManager: UIView {
/// Transition object for animation between fragment
open lazy var transition: CATransition = {
let transition = CATransition()
transition.duration = 0.3
transition.type = CATransitionType.reveal
transition.subtype = CATransitionSubtype(rawValue: CATransitionType.reveal.rawValue)
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
return transition
}()
/// Fragment previous transition
open var prevTransition: String = convertFromCATransitionSubtype(.fromLeft)
/// Fragment next transition
open var nextTransition: String = convertFromCATransitionSubtype(.fromRight)
/// Parent View Controller
open var parentViewController: UIViewController?
/// Selected Fragment Index
open var selectedIndex: Int = 0
/// View Controllers
var viewControllers = [UIViewController]()
/// Fragments
var fragments = [AAFragment]()
/// Animation Identifier
var animIdentifier = "AAFragmentManager"
/// Instance Identifer
static var identifier = "AAFragmentManager"
/// Instance
static var instance: AAFragmentManager? {
get {
return getInstance(key: AAFragmentManager.identifier)
}
set {
setInstance(obj: newValue, key: AAFragmentManager.identifier)
}
}
/// Init function
///
/// - Parameter frame: frame
override init (frame : CGRect) {
super.init(frame : frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Initialize the AAFragmentManager
///
/// - Parameter viewControllers: Collection of UIViewController
open func initManager(viewControllers: [UIViewController]) {
self.viewControllers = viewControllers
setTransition(transition: transition)
current()
}
/// Initialize the AAFragmentManager
///
/// - Parameters:
/// - viewControllers: Collection of UIViewController
/// - parentViewController: Super view controller for reference
/// - identifier: Instance identifier
open func initManager(viewControllers: [UIViewController],
parentViewController: UIViewController,
identifier: AAFragmentManagerInstance) {
self.parentViewController = parentViewController
AAFragmentManager.identifier = identifier._id
AAFragmentManager.instance = self
initManager(viewControllers: viewControllers)
}
/// Initialize the AAFragmentManager
///
/// - Parameter fragments: Collection of AAFragment
open func initManager(fragments: [AAFragment]) {
let viewControllers = getViewControllers(fromFragments: fragments)
initManager(viewControllers: viewControllers)
}
/// Initialize the AAFragmentManager
///
/// - Parameters:
/// - fragments: Collection of AAFragment
/// - parentViewController: Super view controller for reference
/// - identifier: Instance identifier
open func initManager(fragments: [AAFragment],
parentViewController: UIViewController,
identifier: AAFragmentManagerInstance) {
let viewControllers = getViewControllers(fromFragments: fragments)
initManager(viewControllers: viewControllers, parentViewController: parentViewController, identifier: identifier)
}
func replaceFragment(view: UIView, insets: UIEdgeInsets, animate: Bool) {
removeSubviews()
animateFragment(animate)
addAndFitSubview(view, insets: insets)
}
/// Animates the fragment if required
private func animateFragment(_ animate: Bool) {
if animate {
self.layer.add(transition, forKey: animIdentifier)
}
else {
self.layer.removeAnimation(forKey: animIdentifier)
}
}
/// Converts the collection of AAFragment to the view controllers
func getViewControllers(fromFragments: [AAFragment]) -> [UIViewController] {
self.fragments = fromFragments
return fragments.compactMap { $0.viewsController }
}
/// Empty current view
func removeSubviews() {
subviews.forEach({$0.removeFromSuperview()})
}
/// Adds the current fragment in superview
func current() {
replace(withIndex: selectedIndex, animate: false)
}
}
// MARK: - Public methods
extension AAFragmentManager {
/// Replaces with the next fragment if available
open func next(_ animate: Bool = true) {
let nextIndex = selectedIndex + 1
replace(withIndex: nextIndex, animate: animate)
}
/// Replaces with the previous fragment if available
open func previous(_ animate: Bool = true) {
let nextIndex = selectedIndex - 1
replace(withIndex: nextIndex, animate: animate)
}
/// Sets the transition for replacing the fragments
open func setTransition(transition: CATransition) {
self.transition = transition
}
/// Replaces with the previous fragment if available
///
/// - Parameters:
/// - index: Index of required fragment
/// - insets: fragment insets
/// - nextPrevTransition: default next and previous transitions
/// - animate: should animate while replacing
open func replace(withIndex index: Int,
insets: UIEdgeInsets = .zero,
nextPrevTransition: Bool = true,
animate: Bool = true) {
guard let view = viewControllers[optional: index]?.view else { return }
if nextPrevTransition {
self.transition.subtype = convertToOptionalCATransitionSubtype(selectedIndex > index ? prevTransition : nextTransition)
}
selectedIndex = index
replaceFragment(view: view, insets: insets, animate: animate)
}
open func replace(withfragment fragment: AAFragment,
insets: UIEdgeInsets = .zero,
animate: Bool = true) {
guard let view = fragment.viewsController.view else { return }
replaceFragment(view: view, insets: insets, animate: animate)
}
/// Get the fragment by index
open func getFragment(withIndex: Int) -> UIViewController? {
return viewControllers[optional: withIndex]
}
/// Get the fragment by AAFragment
open func getFragment(fragment: AAFragment) -> UIViewController? {
return self.fragments.filter { $0 == fragment }.first?.viewsController
}
/// Get view controllers with identifiers in specific storyboard
open class func getViewControllers(withIds: [String], storyboard: String) -> [UIViewController] {
return withIds.compactMap { (idd) -> UIViewController in
let storyboard: UIStoryboard = UIStoryboard(name: storyboard, bundle: nil)
return storyboard.instantiateViewController(withIdentifier: idd)
}
}
/// Get instance with identifier
class open func getInstance(withIdentifier: AAFragmentManagerInstance) -> AAFragmentManager? {
AAFragmentManager.identifier = withIdentifier._id
return AAFragmentManager.instance
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromCATransitionSubtype(_ input: CATransitionSubtype) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalCATransitionSubtype(_ input: String?) -> CATransitionSubtype? {
guard let input = input else { return nil }
return CATransitionSubtype(rawValue: input)
}
| mit | 309348dcb9ce4f85cd4c93fc2da24524 | 32.55144 | 131 | 0.650681 | 5.431712 | false | false | false | false |
LeeShiYoung/DouYu | DouYuAPP/DouYuAPP/Classes/Main/Tools/Notifier.swift | 1 | 1440 | //
// Notifier.swift
// DouYuAPP
//
// Created by shying li on 2017/4/14.
// Copyright © 2017年 李世洋. All rights reserved.
//
import Foundation
public protocol Notifier {
associatedtype Notification: RawRepresentable
}
public extension Notifier where Notification.RawValue == String {
private static func nameFor(Notification notification: Notification) -> String {
return "\(self).\(notification.rawValue)"
}
/// post
static func postNotification(notification: Notification, object: AnyObject? = nil, userInfo: [String : AnyObject]? = nil) {
let name = nameFor(Notification: notification)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object, userInfo: userInfo)
}
/// Add
static func addObserver(observer: AnyObject, selector: Selector, notification: Notification) {
let name = nameFor(Notification: notification)
NotificationCenter.default.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
}
/// Remove
static func removeObserver(observer: AnyObject, notification: Notification, object: AnyObject? = nil) {
let name = nameFor(Notification: notification)
NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: name), object: object)
}
}
| apache-2.0 | 9034cb564fe2bd0e96ad7c4be75cf079 | 27.058824 | 132 | 0.684836 | 4.917526 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/views/NodesMap.swift | 1 | 851 |
import UIKit
let nodesMap = NodesMap()
var parentsMap = [Node: Set<Node>]()
class NodesMap {
var map = [Node: MacawView]()
// MARK: - Macaw View
func add(_ node: Node, view: MacawView) {
map[node] = view
if let group = node as? Group {
group.contents.forEach { child in
self.add(child, view: view)
self.add(child, parent: node)
}
}
}
func getView(_ node: Node) -> MacawView? {
return map[node]
}
func remove(_ node: Node) {
map.removeValue(forKey: node)
parentsMap.removeValue(forKey: node)
}
// MARK: - Parents
func add(_ node: Node, parent: Node) {
if var nodesSet = parentsMap[node] {
nodesSet.insert(parent)
} else {
parentsMap[node] = Set([parent])
}
}
func parents(_ node: Node) -> [Node] {
guard let nodesSet = parentsMap[node] else {
return []
}
return Array(nodesSet)
}
}
| mit | b3e459f3438ca92cc38850d446284220 | 17.106383 | 46 | 0.627497 | 2.836667 | false | false | false | false |
omise/omise-ios | OmiseSDKTests/InvalidCardAPIErrorParsingTestCase.swift | 1 | 9516 | import XCTest
@testable import OmiseSDK
// swiftlint:disable function_body_length
class InvalidCardAPIErrorParsingTestCase: XCTestCase {
func testParseInvalidCardNumber() throws {
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "number can't be blank and brand not supported (unknown)"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidCardNumber])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "number is invalid and brand not supported (unknown)"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidCardNumber])
} else {
XCTFail("Parsing results with the wrong code")
}
}
}
func testParseEmptyCardHolderName() throws {
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "name can't be blank"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.emptyCardHolderName])
} else {
XCTFail("Parsing results with the wrong code")
}
}
}
func testParseInvalidExpirationDate() throws {
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration date cannot be in the past"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration year is invalid"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration month is not between 1 and 12, expiration year is invalid, and expiration date is invalid"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration month is not between 1 and 12 and expiration date is invalid"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [OmiseError.APIErrorCode.InvalidCardReason.invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
}
func testParseErrorWithMultipleReasons() throws {
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration year is invalid, number is invalid, and brand not supported (unknown)"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [.invalidCardNumber, .invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "name can't be blank, expiration year is invalid, number is invalid, and brand not supported (unknown)"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [.invalidCardNumber, .invalidExpirationDate, .emptyCardHolderName])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
// swiftlint:disable line_length
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration month is not between 1 and 12, name can't be blank, expiration year is invalid, expiration date is invalid, number is invalid, and brand not supported (unknown)"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [.invalidCardNumber, .invalidExpirationDate, .emptyCardHolderName])
} else {
XCTFail("Parsing results with the wrong code")
}
}
do {
let errorJSONString = """
{
"object": "error",
"location": "https://www.omise.co/api-errors#invalid-card",
"code": "invalid_card",
"message": "expiration month can't be blank and expiration month is not between 1 and 12"
}
"""
let decoder = JSONDecoder()
let parsedError = try decoder.decode(OmiseError.self, from: Data(errorJSONString.utf8))
if case .api(code: .invalidCard(let reasons), message: _, location: _) = parsedError {
XCTAssertEqual(reasons, [.invalidExpirationDate])
} else {
XCTFail("Parsing results with the wrong code")
}
}
}
}
| mit | f68bd96c60db272908ff0f1116f59af0 | 41.293333 | 202 | 0.518285 | 4.976987 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/TabPeekViewController.swift | 2 | 8783 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import Shared
import Storage
import WebKit
protocol TabPeekDelegate: AnyObject {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var fxaDevicePicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
fileprivate var webView: WKWebView?
// Preview action items.
override var previewActionItems: [UIPreviewActionItem] { return previewActions }
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
let isHomeTab = self.tab?.isFxHomeTab ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked && !isHomeTab {
actions.append(UIPreviewAction(title: .TabPeekAddToBookmarks, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: .AppMenu.TouchActions.SendToDeviceTitle, style: .default) { [weak self] previewAction, viewController in
guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: .TabPeekCopyUrl, style: .default) {[weak self] previewAction, viewController in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(.AppMenu.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
}
actions.append(UIPreviewAction(title: .TabPeekCloseTab, style: .destructive) { [weak self] previewAction, viewController in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
func contextActions(defaultActions: [UIMenuElement]) -> UIMenu {
var actions = [UIAction]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
let isHomeTab = self.tab?.isFxHomeTab ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isBookmarked && !isHomeTab {
actions.append(UIAction(title: .TabPeekAddToBookmarks, image: UIImage.templateImageNamed(ImageIdentifiers.addToBookmark), identifier: nil) { [weak self] _ in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIAction(title: .AppMenu.TouchActions.SendToDeviceTitle, image: UIImage.templateImageNamed("menu-Send"), identifier: nil) { [weak self] _ in
guard let wself = self, let clientPicker = wself.fxaDevicePicker else { return }
wself.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
actions.append(UIAction(title: .TabPeekCopyUrl, image: UIImage.templateImageNamed(ImageIdentifiers.copyLink), identifier: nil) { [weak self] _ in
guard let wself = self, let url = wself.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(.AppMenu.AppMenuCopyURLConfirmMessage, bottomContainer: wself.view)
})
}
actions.append(UIAction(title: .TabPeekCloseTab,
image: UIImage.templateImageNamed(ImageIdentifiers.closeTap),
identifier: nil) { [weak self] _ in
guard let wself = self, let tab = wself.tab else { return }
wself.delegate?.tabPeekDidCloseTab(tab)
})
return UIMenu(title: "", children: actions)
}
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
webView?.navigationDelegate = nil
self.webView = nil
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: .TabPeekPreviewAccessibilityLabel, webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
if let screenshot = tab?.screenshot {
setupWithScreenshot(screenshot)
} else {
setupWebView(tab?.webView)
}
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView,
let url = webView.url,
!isIgnoredURL(url)
else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
clonedWebView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
self.webView = clonedWebView
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: DevicePickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else { return }
guard let displayURL = tab.url?.absoluteString, !displayURL.isEmpty else { return }
browserProfile.places.isBookmarked(url: displayURL) >>== { isBookmarked in
self.isBookmarked = isBookmarked
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(.main) {
guard let clientGUIDs = $0.successValue else { return }
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = DevicePickerViewController()
clientPickerController.pickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
clientPickerController.profileNeedsShutdown = false
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.fxaDevicePicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList.getRecordWithURL(displayURL).value.successValue
self.isInReadingList = !(result?.url.isEmpty ?? true)
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
| mpl-2.0 | 35652ba8fcd778a44af6e6fff1cad966 | 42.480198 | 173 | 0.652966 | 5.265588 | false | false | false | false |
loudnate/Loop | Common/Models/GlucoseBackfillRequestUserInfo.swift | 1 | 917 | //
// GlucoseBackfillRequestUserInfo.swift
// Loop
//
// Created by Bharat Mediratta on 6/21/18.
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import Foundation
struct GlucoseBackfillRequestUserInfo {
let version = 1
let startDate: Date
}
extension GlucoseBackfillRequestUserInfo: RawRepresentable {
typealias RawValue = [String: Any]
static let name = "GlucoseBackfillRequestUserInfo"
init?(rawValue: RawValue) {
guard
rawValue["v"] as? Int == version,
rawValue["name"] as? String == GlucoseBackfillRequestUserInfo.name,
let startDate = rawValue["sd"] as? Date
else {
return nil
}
self.startDate = startDate
}
var rawValue: RawValue {
return [
"v": version,
"name": GlucoseBackfillRequestUserInfo.name,
"sd": startDate
]
}
}
| apache-2.0 | 73c37b3a8d1e89a4982bf2aa66767e9a | 21.9 | 79 | 0.613537 | 4.320755 | false | false | false | false |
sprejjs/pitch_perfect | Sound Recorder/RecordSoundsViewController.swift | 1 | 2786 | //
// ViewController.swift
// Sound Recorder
//
// Created by Vlad Spreys on 26/02/15.
// Copyright (c) 2015 Spreys.com. All rights reserved.
//
import AVFoundation
import UIKit
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var lblRecording: UILabel!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var recordButton: UIButton!
var audioRecorder:AVAudioRecorder!
var recordedAudio: RecordedAudio!
override func viewWillAppear(animated: Bool){
super.viewWillAppear(animated)
self.stopButton.hidden = true
self.lblRecording.text = "Tap to Record"
}
@IBAction func recordAudio(sender: UIButton) {
self.lblRecording.text = "Recording"
self.stopButton.hidden = false
self.recordButton.enabled = false
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch _ {
}
audioRecorder = try! AVAudioRecorder(URL: filePath!, settings: [String: AnyObject]())
audioRecorder.meteringEnabled = true
audioRecorder.delegate = self
audioRecorder.record()
}
@IBAction func stopRecording(sender: UIButton) {
self.stopButton.hidden = true
self.recordButton.enabled = true
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
} catch _ {
}
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
if(flag){
recordedAudio = RecordedAudio(url: recorder.url, title: recorder.url.lastPathComponent!)
self.performSegueWithIdentifier("stopRecording", sender: recordedAudio)
} else {
print("Recording wasn't successfull")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "stopRecording"){
let playSoundVC = segue.destinationViewController as! PlaySoundsViewController
let data = sender as! RecordedAudio
playSoundVC.receivedAudio = data
}
}
}
| mit | 44c474fc5985b73aa7854b2ec209d8ce | 31.395349 | 113 | 0.655061 | 5.388781 | false | false | false | false |
remobjects/Marzipan | CodeGen4/Expressions.swift | 1 | 20244 | /* Expressions */
public __abstract class CGExpression: CGStatement {
}
public class CGRawExpression : CGExpression { // not language-agnostic. obviosuly.
public var Lines: List<String>
public init(_ lines: List<String>) {
Lines = lines
}
/*public convenience init(_ lines: String ...) {
init(lines.ToList())
}*/
public init(_ lines: String) {
Lines = lines.Replace("\r", "").Split("\n").MutableVersion()
}
}
public class CGTypeReferenceExpression : CGExpression{
public var `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
}
}
public class CGAssignedExpression: CGExpression {
public var Value: CGExpression
public var Inverted: Boolean = false
public init(_ value: CGExpression) {
Value = value
}
public init(_ value: CGExpression, inverted: Boolean) {
Value = value
Inverted = inverted
}
}
public class CGSizeOfExpression: CGExpression {
public var Expression: CGExpression
public init(_ expression: CGExpression) {
Expression = expression
}
}
public class CGTypeOfExpression: CGExpression {
public var Expression: CGExpression
public init(_ expression: CGExpression) {
Expression = expression
}
}
public class CGDefaultExpression: CGExpression {
public var `Type`: CGTypeReference
public init(_ type: CGTypeReference) {
`Type` = type
}
}
public class CGSelectorExpression: CGExpression { /* Cocoa only */
public var Name: String
public init(_ name: String) {
Name = name
}
}
public class CGTypeCastExpression: CGExpression {
public var Expression: CGExpression
public var TargetType: CGTypeReference
public var ThrowsException = false
public var GuaranteedSafe = false // in Silver, this uses "as"
public var CastKind: CGTypeCastKind? // C++ only
public init(_ expression: CGExpression, _ targetType: CGTypeReference) {
Expression = expression
TargetType = targetType
}
public convenience init(_ expression: CGExpression, _ targetType: CGTypeReference, _ throwsException: Boolean) {
init(expression, targetType)
ThrowsException = throwsException
}
}
public enum CGTypeCastKind { // C++ only
case Constant
case Dynamic
case Reinterpret
case Static
case Interface // C++Builder only
case Safe // VC++ only
}
public class CGAwaitExpression: CGExpression {
public var Expression: CGExpression
public init(_ expression: CGExpression) {
Expression = expression
}
}
public class CGAnonymousMethodExpression: CGExpression {
public var Lambda = true
public var Parameters: List<CGParameterDefinition>
public var ReturnType: CGTypeReference?
public var Statements: List<CGStatement>
public var LocalVariables: List<CGVariableDeclarationStatement>? // Legacy Delphi only.
public init(_ statements: List<CGStatement>) {
super.init()
Parameters = List<CGParameterDefinition>()
Statements = statements
}
public convenience init(_ statements: CGStatement...) {
init(statements.ToList())
}
public init(_ parameters: List<CGParameterDefinition>, _ statements: List<CGStatement>) {
super.init()
Statements = statements
Parameters = parameters
}
public convenience init(_ parameters: CGParameterDefinition[], _ statements: CGStatement[]) {
init(parameters.ToList(), statements.ToList())
}
}
public enum CGAnonymousTypeKind {
case Class
case Struct
case Interface
}
public class CGAnonymousTypeExpression : CGExpression {
public var Kind: CGAnonymousTypeKind
public var Ancestor: CGTypeReference?
public var Members = List<CGAnonymousMemberDefinition>()
public init(_ kind: CGAnonymousTypeKind) {
Kind = kind
}
}
public __abstract class CGAnonymousMemberDefinition : CGEntity{
public var Name: String
public init(_ name: String) {
Name = name
}
}
public class CGAnonymousPropertyMemberDefinition : CGAnonymousMemberDefinition{
public var Value: CGExpression
public init(_ name: String, _ value: CGExpression) {
super.init(name)
Value = value
}
}
public class CGAnonymousMethodMemberDefinition : CGAnonymousMemberDefinition{
public var Parameters = List<CGParameterDefinition>()
public var ReturnType: CGTypeReference?
public var Statements: List<CGStatement>
public init(_ name: String, _ statements: List<CGStatement>) {
super.init(name)
Statements = statements
}
public convenience init(_ name: String, _ statements: CGStatement...) {
init(name, statements.ToList())
}
}
public class CGInheritedExpression: CGExpression {
public static lazy let Inherited = CGInheritedExpression()
}
public class CGIfThenElseExpression: CGExpression { // aka Ternary operator
public var Condition: CGExpression
public var IfExpression: CGExpression
public var ElseExpression: CGExpression?
public init(_ condition: CGExpression, _ ifExpression: CGExpression, _ elseExpression: CGExpression?) {
Condition = condition
IfExpression= ifExpression
ElseExpression = elseExpression
}
}
/*
public class CGSwitchExpression: CGExpression { //* Oxygene only */
//incomplete
}
public class CGSwitchExpressionCase : CGEntity {
public var CaseExpression: CGExpression
public var ResultExpression: CGExpression
public init(_ caseExpression: CGExpression, _ resultExpression: CGExpression) {
CaseExpression = caseExpression
ResultExpression = resultExpression
}
}
public class CGForToLoopExpression: CGExpression { //* Oxygene only */
//incomplete
}
public class CGForEachLoopExpression: CGExpression { //* Oxygene only */
//incomplete
}
*/
public class CGPointerDereferenceExpression: CGExpression {
public var PointerExpression: CGExpression
public init(_ pointerExpression: CGExpression) {
PointerExpression = pointerExpression
}
}
public class CGParenthesesExpression: CGExpression {
public var Value: CGExpression
public init(_ value: CGExpression) {
Value = value
}
}
public class CGRangeExpression: CGExpression {
public var StartValue: CGExpression
public var EndValue: CGExpression
public init(_ startValue: CGExpression, _ endValue: CGExpression) {
StartValue = startValue
EndValue = endValue
}
}
public class CGUnaryOperatorExpression: CGExpression {
public var Value: CGExpression
public var Operator: CGUnaryOperatorKind? // for standard operators
public var OperatorString: String? // for custom operators
public init(_ value: CGExpression, _ `operator`: CGUnaryOperatorKind) {
Value = value
Operator = `operator`
}
public init(_ value: CGExpression, _ operatorString: String) {
Value = value
OperatorString = operatorString
}
public static func NotExpression(_ value: CGExpression) -> CGUnaryOperatorExpression {
return CGUnaryOperatorExpression(value, CGUnaryOperatorKind.Not)
}
}
public enum CGUnaryOperatorKind {
case Plus
case Minus
case Not
case AddressOf
case ForceUnwrapNullable
case BitwiseNot
}
public class CGBinaryOperatorExpression: CGExpression {
public var LefthandValue: CGExpression
public var RighthandValue: CGExpression
public var Operator: CGBinaryOperatorKind? // for standard operators
public var OperatorString: String? // for custom operators
public init(_ lefthandValue: CGExpression, _ righthandValue: CGExpression, _ `operator`: CGBinaryOperatorKind) {
LefthandValue = lefthandValue
RighthandValue = righthandValue
Operator = `operator`
}
public init(_ lefthandValue: CGExpression, _ righthandValue: CGExpression, _ operatorString: String) {
LefthandValue = lefthandValue
RighthandValue = righthandValue
OperatorString = operatorString
}
}
public enum CGBinaryOperatorKind {
case Concat // string concat, can be different than +
case Addition
case Subtraction
case Multiplication
case Division
case LegacyPascalDivision // "div"
case Modulus
case Equals
case NotEquals
case LessThan
case LessThanOrEquals
case GreaterThan
case GreatThanOrEqual
case LogicalAnd
case LogicalOr
case LogicalXor
case Shl
case Shr
case BitwiseAnd
case BitwiseOr
case BitwiseXor
case Implies /* Oxygene only */
case Is
case IsNot
case In /* Oxygene only */
case NotIn /* Oxygene only */
case Assign
case AssignAddition
case AssignSubtraction
case AssignMultiplication
case AssignDivision
/*case AssignModulus
case AssignBitwiseAnd
case AssignBitwiseOr
case AssignBitwiseXor
case AssignShl
case AssignShr*/
case AddEvent
case RemoveEvent
}
/* Literal Expressions */
public class CGNamedIdentifierExpression: CGExpression {
public var Name: String
public init(_ name: String) {
Name = name
}
}
public class CGSelfExpression: CGExpression { // "self" or "this"
public static lazy let `Self` = CGSelfExpression()
}
public class CGNilExpression: CGExpression { // "nil" or "null"
public static lazy let Nil = CGNilExpression()
}
public class CGPropertyValueExpression: CGExpression { /* "value" or "newValue" in C#/Swift */
public static lazy let PropertyValue = CGPropertyValueExpression()
}
public class CGLiteralExpression: CGExpression {
}
public __abstract class CGLanguageAgnosticLiteralExpression: CGExpression {
internal __abstract func StringRepresentation() -> String
}
public class CGStringLiteralExpression: CGLiteralExpression {
public var Value: String = ""
public static lazy let Empty: CGStringLiteralExpression = "".AsLiteralExpression()
public static lazy let Space: CGStringLiteralExpression = " ".AsLiteralExpression()
public init() {
}
public init(_ value: String) {
Value = value
}
}
public class CGCharacterLiteralExpression: CGLiteralExpression {
public var Value: Char = "\0"
//public static lazy let Zero: CGCharacterLiteralExpression = "\0".AsLiteralExpression()
public static lazy let Zero = CGCharacterLiteralExpression("\0")
public init() {
}
public init(_ value: Char) {
Value = value
}
}
public class CGIntegerLiteralExpression: CGLanguageAgnosticLiteralExpression {
public var SignedValue: Int64? = nil {
didSet {
if SignedValue != nil {
UnsignedValue = nil
}
}
}
public var UnsignedValue: Int64? = nil {
didSet {
if UnsignedValue != nil {
SignedValue = nil
}
}
}
@Obsolete public var Value: Int64 {
return coalesce(SignedValue, UnsignedValue, 0)
}
public var Base = 10
public var NumberKind: CGNumberKind?
public static lazy let Zero: CGIntegerLiteralExpression = 0.AsLiteralExpression()
public init() {
}
public init(_ value: Int64) {
SignedValue = value
}
public init(_ value: Int64, # base: Int32) {
SignedValue = value
Base = base
}
public init(_ value: UInt64) {
UnsignedValue = value
}
public init(_ value: UInt64, # base: Int32) {
UnsignedValue = value
Base = base
}
override func StringRepresentation() -> String {
return StringRepresentation(base: Base)
}
internal func StringRepresentation(base: Int32) -> String {
if let SignedValue = SignedValue {
return Convert.ToString(SignedValue, base)
} else if let UnsignedValue = UnsignedValue {
return Convert.ToString(UnsignedValue, base)
} else {
return Convert.ToString(0, base)
}
}
}
public class CGFloatLiteralExpression: CGLanguageAgnosticLiteralExpression {
public private(set) var DoubleValue: Double?
public private(set) var IntegerValue: Integer?
public private(set) var StringValue: String?
public var NumberKind: CGNumberKind?
public var Base = 10 // Swift only
public static lazy let Zero: CGFloatLiteralExpression = CGFloatLiteralExpression(0)
public init() {
}
public init(_ value: Double) {
DoubleValue = value
}
public init(_ value: Integer) {
IntegerValue = value
}
public init(_ value: String) {
StringValue = value
}
override func StringRepresentation() -> String {
return StringRepresentation(base: 10)
}
internal func StringRepresentation(# base: Int32) -> String {
switch base {
case 10:
if let value = DoubleValue {
var result = Convert.ToStringInvariant(value)
if !result.Contains(".") {
result += ".0";
}
return result
} else if let value = IntegerValue {
return value.ToString()+".0"
} else if let value = StringValue {
if value.IndexOf(".") > -1 || value.ToLower().IndexOf("e") > -1 {
return value
} else {
return value+".0"
}
} else {
return "0.0"
}
case 16:
if DoubleValue != nil {
throw Exception("base 16 (Hex) float literals with double value are not currently supported.")
} else if let value = IntegerValue {
return Convert.ToString(value, base)+".0"
} else if let value = StringValue {
if value.IndexOf(".") > -1 || value.ToLower().IndexOf("p") > -1 {
return value
} else {
return value+".0"
}
} else {
return "0.0"
}
default:
throw Exception("Base \(base) float literals are not currently supported.")
}
}
}
public class CGImaginaryLiteralExpression: CGFloatLiteralExpression {
internal override func StringRepresentation(# base: Int32) -> String {
return super.StringRepresentation(base: base)+"i";
}
}
public enum CGNumberKind {
case Unsigned, Long, UnsignedLong, Float, Double, Decimal
}
public class CGBooleanLiteralExpression: CGLanguageAgnosticLiteralExpression {
public let Value: Boolean
public static lazy let True = CGBooleanLiteralExpression(true)
public static lazy let False = CGBooleanLiteralExpression(false)
public convenience init() {
init(false)
}
public init(_ bool: Boolean) {
Value = bool
}
override func StringRepresentation() -> String {
if Value {
return "true"
} else {
return "false"
}
}
}
public class CGArrayLiteralExpression: CGExpression {
public var Elements: List<CGExpression>
public var ElementType: CGTypeReference? //c++ only at this moment
public var ArrayKind: CGArrayKind = .Dynamic
public init() {
Elements = List<CGExpression>()
}
public init(_ elements: List<CGExpression>) {
Elements = elements
}
public init(_ elements: List<CGExpression>, _ type: CGTypeReference) {
Elements = elements
ElementType = type
}
public convenience init(_ elements: CGExpression...) {
init(elements.ToList())
}
}
public class CGSetLiteralExpression: CGExpression {
public var Elements: List<CGExpression>
public var ElementType: CGTypeReference?
public init() {
Elements = List<CGExpression>()
}
public init(_ elements: List<CGExpression>) {
Elements = elements
}
public init(_ elements: List<CGExpression>, _ type: CGTypeReference) {
Elements = elements
ElementType = type
}
public convenience init(_ elements: CGExpression...) {
init(elements.ToList())
}
}
public class CGDictionaryLiteralExpression: CGExpression { /* Swift only, currently */
public var Keys: List<CGExpression>
public var Values: List<CGExpression>
public init() {
Keys = List<CGExpression>()
Values = List<CGExpression>()
}
public init(_ keys: List<CGExpression>, _ values: List<CGExpression>) {
Keys = keys
Values = values
}
public convenience init(_ keys: CGExpression[], _ values: CGExpression[]) {
init(keys.ToList(), values.ToList())
}
}
public class CGTupleLiteralExpression : CGExpression {
public var Members: List<CGExpression>
public init(_ members: List<CGExpression>) {
Members = members
}
public convenience init(_ members: CGExpression...) {
init(members.ToList())
}
}
/* Calls */
public class CGNewInstanceExpression : CGExpression {
public var `Type`: CGExpression
public var ConstructorName: String? // can optionally be provided for languages that support named .ctors (Elements, Objectice-C, Swift)
public var Parameters: List<CGCallParameter>
public var ArrayBounds: List<CGExpression>? // for array initialization.
public var PropertyInitializers = List<CGPropertyInitializer>() // for Oxygene and C# extended .ctor calls
public convenience init(_ type: CGTypeReference) {
init(type.AsExpression())
}
public convenience init(_ type: CGTypeReference, _ parameters: List<CGCallParameter>) {
init(type.AsExpression(), parameters)
}
public convenience init(_ type: CGTypeReference, _ parameters: CGCallParameter...) {
init(type.AsExpression(), parameters)
}
public init(_ type: CGExpression) {
`Type` = type
Parameters = List<CGCallParameter>()
}
public init(_ type: CGExpression, _ parameters: List<CGCallParameter>) {
`Type` = type
Parameters = parameters
}
public convenience init(_ type: CGExpression, _ parameters: CGCallParameter...) {
init(type, parameters.ToList())
}
}
public class CGDestroyInstanceExpression : CGExpression {
public var Instance: CGExpression;
public init(_ instance: CGExpression) {
Instance = instance;
}
}
public class CGLocalVariableAccessExpression : CGExpression {
public var Name: String
public var NilSafe: Boolean = false // true to use colon or elvis operator
public var UnwrapNullable: Boolean = false // Swift only
public init(_ name: String) {
Name = name
}
}
public enum CGCallSiteKind {
case Unspecified
case Static
case Instance
case Reference
}
public __abstract class CGMemberAccessExpression : CGExpression {
public var CallSite: CGExpression? // can be nil to call a local or global function/variable. Should be set to CGSelfExpression for local methods.
public var Name: String
public var NilSafe: Boolean = false // true to use colon or elvis operator
public var UnwrapNullable: Boolean = false // Swift only
public var CallSiteKind: CGCallSiteKind = .Unspecified //C++ only
public init(_ callSite: CGExpression?, _ name: String) {
CallSite = callSite
Name = name
}
}
public class CGFieldAccessExpression : CGMemberAccessExpression {
}
public class CGEventAccessExpression : CGFieldAccessExpression {
}
public class CGEnumValueAccessExpression : CGExpression {
public var `Type`: CGTypeReference
public var ValueName: String
public init(_ type: CGTypeReference, _ valueName: String) {
`Type` = type
ValueName = valueName
}
}
public class CGMethodCallExpression : CGMemberAccessExpression{
public var Parameters: List<CGCallParameter>
public var GenericArguments: List<CGTypeReference>?
public var CallOptionally: Boolean = false // Swift only
public init(_ callSite: CGExpression?, _ name: String) {
super.init(callSite, name)
Parameters = List<CGCallParameter>()
}
public init(_ callSite: CGExpression?, _ name: String, _ parameters: List<CGCallParameter>?) {
super.init(callSite, name)
if let parameters = parameters {
Parameters = parameters
} else {
Parameters = List<CGCallParameter>()
}
}
public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) {
init(callSite, name, List<CGCallParameter>(parameters))
}
}
public class CGPropertyAccessExpression: CGMemberAccessExpression {
public var Parameters: List<CGCallParameter>
public init(_ callSite: CGExpression?, _ name: String, _ parameters: List<CGCallParameter>?) {
super.init(callSite, name)
if let parameters = parameters {
Parameters = parameters
} else {
Parameters = List<CGCallParameter>()
}
}
public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) {
init(callSite, name, List<CGCallParameter>(parameters))
}
}
public class CGCallParameter: CGEntity {
public var Name: String? // optional, for named parameters or prooperty initialziers
public var Value: CGExpression
public var Modifier: CGParameterModifierKind = .In
public var EllipsisParameter: Boolean = false // used mainly for Objective-C, wioch needs a different syntax when passing elipsis paframs
public init(_ value: CGExpression) {
Value = value
}
public init(_ value: CGExpression, _ name: String) {
//public init(value) // 71582: Silver: delegating to a second .ctor doesn't properly detect that a field will be initialized
Value = value
Name = name
}
}
public class CGPropertyInitializer: CGEntity {
public var Name: String
public var Value: CGExpression
public init(_ name: String, _ value: CGExpression) {
Value = value
Name = name
}
}
public class CGArrayElementAccessExpression: CGExpression {
public var Array: CGExpression
public var Parameters: List<CGExpression>
public init(_ array: CGExpression, _ parameters: List<CGExpression>) {
Array = array
Parameters = parameters
}
public convenience init(_ array: CGExpression, _ parameters: CGExpression...) {
init(array, parameters.ToList())
}
} | bsd-3-clause | c70a8c4037d2a522510d3b54cf7342bd | 25.153747 | 147 | 0.739156 | 3.701902 | false | false | false | false |
alvinvarghese/JSONCodable | Demo/Demo/ViewController.swift | 3 | 1574 | //
// ViewController.swift
// Demo
//
// Created by Matthew Cheok on 18/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let JSON = [
"id": 24,
"full_name": "John Appleseed",
"email": "[email protected]",
"company": [
"name": "Apple",
"address": "1 Infinite Loop, Cupertino, CA"
],
"friends": [
["id": 27, "full_name": "Bob Jefferson"],
["id": 29, "full_name": "Jen Jackson"]
]
]
print("Initial JSON:\n\(JSON)\n\n")
let user = User(JSONDictionary: JSON)!
print("Decoded: \n\(user)\n\n")
do {
let dict = try user.toJSON()
print("Encoded: \n\(dict as! [String: AnyObject])\n\n")
}
catch {
print("Error: \(error)")
}
//do {
// let string = try user.JSONString()
// print(string)
//
// let userAgain = User(JSONString: string)
// print(userAgain)
//} catch {
// print("Error: \(error)")
//}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 809a6cef6494d5eca672fd7a39f610b8 | 23.2 | 80 | 0.472346 | 4.345304 | false | false | false | false |
prolificinteractive/GenericValidator | Sources/Extensions/String+Evaluatable.swift | 1 | 2675 | //
// String+Evaluatable.swift
// GenericValidator
//
// Created by Thibault Klein on 11/29/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
public extension String {
/// Evaluates the given condition.
///
/// - Parameter condition: The condition to evaluate
/// - Returns: `true` if and only if the condition passed the evaluation.
func evaluate(with condition: String) -> Bool {
guard let range = range(of: condition, options: .regularExpression, range: nil, locale: nil) else {
return false
}
return range.lowerBound == startIndex && range.upperBound == endIndex
}
/// Indicates if the text field's text is not empty.
///
/// - Returns: `true` if and only if the text is not empty.
func isNotEmpty() -> Bool {
return !isEmpty
}
/// Indicates if the phone number is valid.
///
/// - Returns: `true` if and only if the text is a phone number.
func isPhoneNumberValid() -> Bool {
var cleanedText = replacingOccurrences(of: "-", with: "")
cleanedText = cleanedText.replacingOccurrences(of: "(", with: "")
cleanedText = cleanedText.replacingOccurrences(of: ")", with: "")
cleanedText = cleanedText.replacingOccurrences(of: " ", with: "")
cleanedText = cleanedText.replacingOccurrences(of: ".", with: "")
cleanedText = cleanedText.replacingOccurrences(of: "/", with: "")
let regexp = "^[0-9]{10}$"
return cleanedText.evaluate(with: regexp)
}
/// Indicates if the zip code is valid.
///
/// - Returns: `true` if and only if the text is a zip code.
func isZipCodeValid() -> Bool {
let regexp = "^[0-9]{5}$"
return evaluate(with: regexp)
}
/// Indicates if the US state is valid.
///
/// - Returns: `true` if and only if the text is a state.
func isStateValid() -> Bool {
let regexp = "^[A-Z]{2}$"
return evaluate(with: regexp)
}
/// Indicates if the credit card CVC number is valid.
///
/// - Returns: `true` if the text is a valid credit card CVC number.
func isCVCValid() -> Bool {
let regexp = "^[0-9]{3,4}$"
return evaluate(with: regexp)
}
/// Indicates if the email is valid.
///
/// - Returns: `true` if and only if the text is a valid email.
func isEmailValid() -> Bool {
guard let firstChar = unicodeScalars.first else {
return false
}
let regexp = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
return evaluate(with: regexp) && firstChar.isAlphaNumeric()
}
}
| mit | 9c2f8de8e40dd8c75a6f169a8cd3920e | 32.425 | 107 | 0.588631 | 4.101227 | false | false | false | false |
josherick/DailySpend | DailySpend/OldTodayViewController.swift | 1 | 21100 | //
// TodayViewController.swift
// DailySpend
//
// Created by Josh Sherick on 3/6/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import UIKit
import CoreData
class OldTodayViewController : UIViewController,
AddExpenseTableViewCellDelegate, UITableViewDataSource, UITableViewDelegate {
let standardCellHeight: CGFloat = 44
let addExpenseMinPxVisible: CGFloat = 70
var currentDayHeight: CGFloat {
let baseHeight: CGFloat = 140
let heightOfTodaysSpendingLabel: CGFloat = 21
if daysThisMonth.last == nil ||
daysThisMonth.last!.expenses!.count == 0 {
return baseHeight - heightOfTodaysSpendingLabel
} else {
return baseHeight
}
}
var addExpenseHeight: CGFloat {
let baseHeight: CGFloat = 400
if addingExpense {
return visibleHeight
} else {
return baseHeight
}
}
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
var context: NSManagedObjectContext {
return appDelegate.persistentContainer.viewContext
}
var daysThisMonth: [Day] = []
var months: [Month] = []
var addingExpense = false
var previousDailySpendLeft: Decimal = 0
var adjustBarButton: UIBarButtonItem?
var settingsBarButton: UIBarButtonItem?
@IBOutlet weak var tableView: UITableView!
// Required for unwind segue
@IBAction override func prepare(for segue: UIStoryboardSegue, sender: Any?) {}
func promptForDailyTargetSpend() {
let sb = storyboard!
let id = "InitialSpend"
let navController = sb.instantiateViewController(withIdentifier: id)
navController.modalPresentationStyle = .fullScreen
navController.modalTransitionStyle = .coverVertical
self.present(navController, animated: true, completion: nil)
}
@objc func willEnterForeground() {
let sortDesc = NSSortDescriptor(key: "date_", ascending: false)
let latestDayResults = Day.get(context: context,
sortDescriptors: [sortDesc],
fetchLimit: 1)!
if latestDayResults.count > 0 &&
latestDayResults[0].calendarDay! < CalendarDay() {
// The day has changed since we last opened the app.
// Refresh.
if addingExpense {
let nc = NotificationCenter.default
nc.post(name: NSNotification.Name.init("CancelAddingExpense"),
object: UIApplication.shared)
}
viewWillAppear(false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if UserDefaults.standard.double(forKey: "dailyTargetSpend") <= 0 {
promptForDailyTargetSpend()
return
}
// Create days up to today.
appDelegate.createUpToToday(notify: false)
refreshData()
Logger.printAllCoreData()
// Reload the data, in case we are coming back a different view that
// changed our data.
tableView.reloadData()
}
@objc func refreshData() {
// Populate daysThisMonth and months
// Fetch all months
let monthSortDesc = NSSortDescriptor(key: "month_", ascending: true)
months = Month.get(context: context, sortDescriptors: [monthSortDesc])!
// Pop this month and get its days.
if let thisMonth = months.popLast() {
let today = CalendarDay()
daysThisMonth = thisMonth.sortedDays!.filter { $0.calendarDay! <= today }
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
let width = navigationController!.navigationBar.frame.size.width * (2 / 3)
let titleLabelView = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: 44))
titleLabelView.backgroundColor = UIColor.clear
titleLabelView.textAlignment = .center
titleLabelView.textColor = UINavigationBar.appearance().tintColor
titleLabelView.font = UIFont.boldSystemFont(ofSize: 16.0)
titleLabelView.text = "Spending"
self.navigationItem.titleView = titleLabelView
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(willEnterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
nc.addObserver(self,
selector: #selector(refreshData),
name: Notification.Name.init("AddedNewDays"),
object: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.0001) {
if UserDefaults.standard.double(forKey: "dailyTargetSpend") > 0 {
let currentDayPath = IndexPath(row: self.currentDayCellIndex,
section: 0)
self.tableView.scrollToRow(at: currentDayPath,
at: .top, animated: false)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Functions for managment of CoreData */
/*
* Calculates the number of on-screen spots for expenses (including "see
* additional" spots) while keeping addExpenseMinPxVisible pixels visible in
* the addExpense cell
*/
var maxExpenseSpots: Int {
// Swift integer division...
let spaceForExpenses = visibleHeight - currentDayHeight - addExpenseMinPxVisible
return Int(floor(Double(spaceForExpenses) / Double(standardCellHeight)))
}
/*
* Calculates the number of on-screen spots taking into account the actual
* number of expenses.
*/
var numExpenseSpots: Int {
let totalExpenses = daysThisMonth.last?.expenses?.count ?? 0
return min(totalExpenses, maxExpenseSpots)
}
var lastPrevDayCellIndex: Int {
return months.count + daysThisMonth.count - 2
}
var currentDayCellIndex: Int {
return lastPrevDayCellIndex + 1
}
var lastExpenseCellIndex: Int {
return currentDayCellIndex + numExpenseSpots
}
var addExpenseCellIndex: Int {
return lastExpenseCellIndex + 1
}
var blankCellIndex: Int {
return addExpenseCellIndex + 1
}
var heightUsed: CGFloat {
let expensesHeight = CGFloat(numExpenseSpots) * standardCellHeight
return currentDayHeight + expensesHeight + addExpenseHeight
}
var visibleHeight: CGFloat {
let topHeight = UIApplication.shared.statusBarFrame.height +
self.navigationController!.navigationBar.frame.height
let windowFrameHeight = UIScreen.main.bounds.size.height
return windowFrameHeight - topHeight;
}
/* Table view data source methods */
// enum TodayViewCellType {
// case MonthCell
// case DayCell
// case TodayCell
// case ExpenseCell
// case ExtraExpensesCell
// case AddExpenseCell
// }
//
// func cellTypeForIndexPath(indexPath: IndexPath) -> TodayViewCellType {
// let section = indexPath.section
// let row = indexPath.row
//
// return .MonthCell
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return months.count +
daysThisMonth.count +
numExpenseSpots +
2
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row <= lastPrevDayCellIndex {
let prevDayCell = tableView.dequeueReusableCell(withIdentifier: "previousDay",
for: indexPath)
if indexPath.row < months.count {
let month = months[indexPath.row]
let dateFormatter = DateFormatter()
let monthsYear = month.calendarMonth!.year
let currentYear = CalendarMonth().year
// Only include the year if it's different than the current year.
dateFormatter.dateFormat = monthsYear != currentYear ? "MMMM YYYY" : "MMMM"
let primaryText = month.calendarMonth!.string(formatter: dateFormatter)
let detailText = String.formatAsCurrency(amount: month.totalExpenses())
let textColor = month.totalExpenses() > month.fullTargetSpend() ? UIColor.overspent : UIColor.underspent
prevDayCell.textLabel?.text = primaryText
prevDayCell.detailTextLabel?.text = detailText
prevDayCell.detailTextLabel?.textColor = textColor
} else {
let day = daysThisMonth[indexPath.row - months.count]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, M/d"
let primaryText = day.calendarDay!.string(formatter: dateFormatter)
let detailText = String.formatAsCurrency(amount: day.totalExpenses())
var textColor = day.leftToCarry() < 0 ? UIColor.overspent : UIColor.underspent
if day.pause != nil {
textColor = UIColor.paused
}
prevDayCell.textLabel?.text = primaryText
prevDayCell.detailTextLabel?.text = detailText
prevDayCell.detailTextLabel?.textColor = textColor
}
return prevDayCell
} else if indexPath.row <= currentDayCellIndex {
let cell = tableView.dequeueReusableCell(withIdentifier: "currentDay",
for: indexPath)
let currentDayCell = cell as! CurrentDayTableViewCell
if let today = daysThisMonth.last {
let dailySpend = today.leftToCarry()
currentDayCell.setAndFormatLabels(dailySpendLeft: dailySpend,
previousDailySpendLeft: previousDailySpendLeft,
expensesToday: today.expenses!.count > 0)
previousDailySpendLeft = dailySpend
}
return currentDayCell
} else if indexPath.row <= lastExpenseCellIndex {
let expenseCell = tableView.dequeueReusableCell(withIdentifier: "expense",
for: indexPath)
let expenses = daysThisMonth.last!.sortedExpenses!
if indexPath.row == lastExpenseCellIndex && expenses.count > numExpenseSpots {
expenseCell.textLabel!.text = "\(expenses.count - numExpenseSpots + 1) more"
var total: Decimal = 0
for expense in expenses.suffix(from: numExpenseSpots - 1) {
total += expense.amount!
}
let detailText = String.formatAsCurrency(amount: total)
expenseCell.detailTextLabel?.text = detailText
} else {
let index = indexPath.row - (currentDayCellIndex + 1)
let amount = expenses[index].amount!.doubleValue
let primaryText = expenses[index].shortDescription
let detailText = String.formatAsCurrency(amount: amount)
expenseCell.textLabel?.text = primaryText
expenseCell.detailTextLabel?.text = detailText
}
return expenseCell
} else if indexPath.row == lastExpenseCellIndex + 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "addExpense",
for: indexPath)
let addExpenseCell = cell as! ExpenseTableViewCell
addExpenseCell.delegate = self
return addExpenseCell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "blank",
for: indexPath)
cell.isUserInteractionEnabled = false
return cell
}
}
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row <= lastPrevDayCellIndex {
return standardCellHeight
} else if indexPath.row <= currentDayCellIndex {
return currentDayHeight
} else if indexPath.row <= lastExpenseCellIndex {
return standardCellHeight
} else if indexPath.row == lastExpenseCellIndex + 1 {
return addExpenseHeight
} else {
return heightUsed < visibleHeight ? visibleHeight - heightUsed : 0
}
}
func tableView(_ tableView: UITableView,
canEditRowAt indexPath: IndexPath) -> Bool {
let bonusExpenses = daysThisMonth.last != nil &&
daysThisMonth.last!.expenses!.count > numExpenseSpots
let lastEditableExpenseCellIndex = lastExpenseCellIndex - (bonusExpenses ? 1 : 0)
return indexPath.row > currentDayCellIndex &&
indexPath.row <= lastEditableExpenseCellIndex
}
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let today = daysThisMonth.last!
let expenses = today.sortedExpenses!
let index = indexPath.row - (currentDayCellIndex + 1)
let expense = expenses[index]
expense.day = nil
context.delete(expense)
appDelegate.saveContext()
tableView.beginUpdates()
if today.expenses!.count < maxExpenseSpots {
tableView.deleteRows(at: [indexPath], with: .none)
} else {
var indexPaths: [IndexPath] = []
let firstExpenseCellIndex = (currentDayCellIndex + 1)
for i in firstExpenseCellIndex...lastExpenseCellIndex {
indexPaths.append(IndexPath(row: i, section: 0))
}
self.tableView.reloadRows(at: indexPaths, with: .none)
}
// Reload current day cell.
let path = IndexPath(row: currentDayCellIndex, section: 0)
self.tableView.reloadRows(at: [path], with: .none)
tableView.endUpdates()
}
}
func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row <= lastExpenseCellIndex {
// Previous day and expense cells are selectable.
return indexPath
} else {
return nil
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let bonusExpenses = daysThisMonth.last == nil ?
false :
daysThisMonth.last!.expenses!.count > numExpenseSpots
if indexPath.row > currentDayCellIndex &&
indexPath.row <= lastExpenseCellIndex - (bonusExpenses ? 1 : 0) {
// Expense (not bonus expense) selected
let expenses = daysThisMonth.last!.sortedExpenses!
let index = indexPath.row - (currentDayCellIndex + 1)
let expenseVC = ExpenseViewController(nibName: nil, bundle: nil)
expenseVC.expense = expenses[index]
self.navigationController?.pushViewController(expenseVC, animated: true)
} else if bonusExpenses && indexPath.row == lastExpenseCellIndex ||
indexPath.row == currentDayCellIndex {
// Bonus expense selected
// Show today.
let dayReviewVC = DayReviewViewController(nibName: nil, bundle: nil)
dayReviewVC.day = daysThisMonth.last!
self.navigationController?.pushViewController(dayReviewVC, animated: true)
} else if indexPath.row < currentDayCellIndex {
if indexPath.row < months.count {
// Month selected
} else {
// Day selected
let dayReviewVC = DayReviewViewController(nibName: nil, bundle: nil)
dayReviewVC.day = daysThisMonth[indexPath.row - months.count]
self.navigationController?.pushViewController(dayReviewVC, animated: true)
}
}
}
/* Add Expense TableView Cell delegate methods */
func expandCell(sender: ExpenseTableViewCell) {
addingExpense = true
self.tableView.isScrollEnabled = false
UIView.animate(withDuration: 0.2, animations: {
self.tableView.beginUpdates()
self.tableView.endUpdates()
})
UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseInOut,
animations: {
self.animateTitle(newTitle: "Add Expense", fromTop: true)
}, completion: nil)
self.tableView.scrollToRow(at: IndexPath(row: addExpenseCellIndex, section: 0),
at: .top, animated: true)
}
func collapseCell(sender: ExpenseTableViewCell) {
self.tableView.isScrollEnabled = true
addingExpense = false
UIView.animate(withDuration: 0.2, animations: {
self.tableView.beginUpdates()
self.tableView.endUpdates()
})
UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseInOut,
animations: {
self.animateTitle(newTitle: "Spending", fromTop: false)
}, completion: nil)
self.tableView.scrollToRow(at: IndexPath(row: currentDayCellIndex, section: 0),
at: .top, animated: true)
}
func addedExpense(expense: Expense) {
if expense.day!.calendarDay! != CalendarDay() {
// This expense isn't for today. Do a full refresh because it
// affected month and day rows.
viewWillAppear(false)
} else {
self.tableView.beginUpdates()
if daysThisMonth.last!.expenses!.count <= numExpenseSpots {
// We have not yet reached bonus expenses, so we will be
// inserting a new row.
let locationOfNewRow = months.count +
daysThisMonth.count +
daysThisMonth.last!.expenses!.count - 1
let indices = [IndexPath(row: locationOfNewRow, section: 0)]
self.tableView.insertRows(at: indices, with: .bottom)
} else {
// There are bonus expenses, just reload the bonus expense cell.
let indices = [IndexPath(row: lastExpenseCellIndex, section: 0)]
tableView.reloadRows(at: indices, with: .none)
}
// Reload the current day cell, since the DailySpend amount changed.
let indices = [IndexPath(row: currentDayCellIndex, section: 0)]
tableView.reloadRows(at: indices, with: .none)
self.tableView.endUpdates()
}
}
func setRightBBI(_ bbi: UIBarButtonItem?) {
navigationItem.rightBarButtonItem = bbi
}
func setLeftBBI(_ bbi: UIBarButtonItem?) {
navigationItem.leftBarButtonItem = bbi
}
func present(_ vc: UIViewController, animated: Bool, completion: (() -> Void)?, sender: Any?) {
self.present(vc, animated: animated, completion: completion)
}
func animateTitle(newTitle: String, fromTop: Bool) {
// Remove old animation, if necessary.
if let keys = navigationItem.titleView!.layer.animationKeys() {
if keys.contains("changeTitle") {
navigationItem.titleView!.layer.removeAnimation(forKey: "changeTitle")
}
}
let titleAnimation = CATransition()
titleAnimation.duration = 0.2
titleAnimation.type = kCATransitionPush
titleAnimation.subtype = fromTop ? kCATransitionFromTop : kCATransitionFromBottom
let timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
titleAnimation.timingFunction = timing
navigationItem.titleView!.layer.add(titleAnimation, forKey: "changeTitle")
(navigationItem.titleView as! UILabel).text = newTitle
}
}
| mit | 3c70962ed268eb15329cc526b5fc09f8 | 39.112167 | 120 | 0.587089 | 5.508877 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Views/ChartPointEllipseView.swift | 7 | 2846 | //
// ChartPointEllipseView.swift
// SwiftCharts
//
// Created by ischuetz on 19/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartPointEllipseView: UIView {
public var fillColor: UIColor = UIColor.grayColor()
public var borderColor: UIColor? = nil
public var borderWidth: CGFloat? = nil
public var animDelay: Float = 0
public var animDuration: Float = 0
public var animateSize: Bool = true
public var animateAlpha: Bool = true
public var animDamping: CGFloat = 1
public var animInitSpringVelocity: CGFloat = 1
public var touchHandler: (() -> ())?
convenience public init(center: CGPoint, diameter: CGFloat) {
self.init(center: center, width: diameter, height: diameter)
}
public init(center: CGPoint, width: CGFloat, height: CGFloat) {
super.init(frame: CGRectMake(center.x - width / 2, center.y - height / 2, width, height))
self.backgroundColor = UIColor.clearColor()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func didMoveToSuperview() {
if self.animDuration != 0 {
if self.animateSize {
self.transform = CGAffineTransformMakeScale(0.1, 0.1)
}
if self.animateAlpha {
self.alpha = 0
}
UIView.animateWithDuration(NSTimeInterval(self.animDuration), delay: NSTimeInterval(self.animDelay), usingSpringWithDamping: self.animDamping, initialSpringVelocity: self.animInitSpringVelocity, options: UIViewAnimationOptions(), animations: { () -> Void in
if self.animateSize {
self.transform = CGAffineTransformMakeScale(1, 1)
}
if self.animateAlpha {
self.alpha = 1
}
}, completion: nil)
}
}
override public func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let borderOffset = self.borderWidth ?? 0
let circleRect = (CGRectMake(borderOffset, borderOffset, self.frame.size.width - (borderOffset * 2), self.frame.size.height - (borderOffset * 2)))
if let borderWidth = self.borderWidth, borderColor = self.borderColor {
CGContextSetLineWidth(context, borderWidth)
CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
CGContextStrokeEllipseInRect(context, circleRect)
}
CGContextSetFillColorWithColor(context, self.fillColor.CGColor)
CGContextFillEllipseInRect(context, circleRect)
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.touchHandler?()
}
}
| mit | 474c2c337d72b7accfd0f503ea569f97 | 36.447368 | 269 | 0.6409 | 5.082143 | false | false | false | false |
andreuke/tasty-imitation-keyboard | Keyboard/KeyboardLayout.swift | 1 | 48012 | //
// KeyboardLayout.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/25/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
// TODO: need to rename, consolidate, and define terms
class LayoutConstants: NSObject {
class var landscapeRatio: CGFloat { get { return 2 }}
// side edges increase on 6 in portrait
class var sideEdgesPortraitArray: [CGFloat] { get { return [3, 4] }}
class var sideEdgesPortraitWidthThreshholds: [CGFloat] { get { return [400] }}
class var sideEdgesLandscape: CGFloat { get { return 3 }}
// top edges decrease on various devices in portrait
class var topEdgePortraitArray: [CGFloat] { get { return [12, 10, 8] }}
class var topEdgePortraitWidthThreshholds: [CGFloat] { get { return [350, 400] }}
class var topEdgeLandscape: CGFloat { get { return 6 }}
// keyboard area shrinks in size in landscape on 6 and 6+
class var keyboardShrunkSizeArray: [CGFloat] { get { return [522, 524] }}
class var keyboardShrunkSizeWidthThreshholds: [CGFloat] { get { return [700] }}
class var keyboardShrunkSizeBaseWidthThreshhold: CGFloat { get { return 600 }}
// row gaps are weird on 6 in portrait
class var rowGapPortraitArray: [CGFloat] { get { return [15, 11, 10] }}
class var rowGapPortraitThreshholds: [CGFloat] { get { return [350, 400] }}
class var rowGapPortraitLastRow: CGFloat { get { return 9 }}
class var rowGapPortraitLastRowIndex: Int { get { return 1 }}
class var rowGapLandscape: CGFloat { get { return 7 }}
// key gaps have weird and inconsistent rules
class var keyGapPortraitNormal: CGFloat { get { return 6 }}
class var keyGapPortraitSmall: CGFloat { get { return 5 }}
class var keyGapPortraitNormalThreshhold: CGFloat { get { return 350 }}
class var keyGapPortraitUncompressThreshhold: CGFloat { get { return 350 }}
class var keyGapLandscapeNormal: CGFloat { get { return 6 }}
class var keyGapLandscapeSmall: CGFloat { get { return 5 }}
// TODO: 5.5 row gap on 5L
// TODO: wider row gap on 6L
class var keyCompressedThreshhold: Int { get { return 11 }}
// rows with two special keys on the side and characters in the middle (usually 3rd row)
// TODO: these are not pixel-perfect, but should be correct within a few pixels
// TODO: are there any "hidden constants" that would allow us to get rid of the multiplier? see: popup dimensions
class var flexibleEndRowTotalWidthToKeyWidthMPortrait: CGFloat { get { return 1 }}
class var flexibleEndRowTotalWidthToKeyWidthCPortrait: CGFloat { get { return -14 }}
class var flexibleEndRowTotalWidthToKeyWidthMLandscape: CGFloat { get { return 0.9231 }}
class var flexibleEndRowTotalWidthToKeyWidthCLandscape: CGFloat { get { return -9.4615 }}
class var flexibleEndRowMinimumStandardCharacterWidth: CGFloat { get { return 7 }}
class var lastRowKeyGapPortrait: CGFloat { get { return 6 }}
class var lastRowKeyGapLandscapeArray: [CGFloat] { get { return [8, 7, 5] }}
class var lastRowKeyGapLandscapeWidthThreshholds: [CGFloat] { get { return [500, 700] }}
// TODO: approxmiate, but close enough
class var lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }}
class var lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }}
class var lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }}
class var lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }}
class var micButtonPortraitWidthRatioToOtherSpecialButtons: CGFloat { get { return 0.765 }}
// TODO: not exactly precise
class var popupGap: CGFloat { get { return 8 }}
class var popupWidthIncrement: CGFloat { get { return 26 }}
class var popupTotalHeightArray: [CGFloat] { get { return [102, 108] }}
class var popupTotalHeightDeviceWidthThreshholds: [CGFloat] { get { return [350] }}
class func sideEdgesPortrait(_ width: CGFloat) -> CGFloat {
return self.findThreshhold(self.sideEdgesPortraitArray, threshholds: self.sideEdgesPortraitWidthThreshholds, measurement: width)
}
class func topEdgePortrait(_ width: CGFloat) -> CGFloat {
return self.findThreshhold(self.topEdgePortraitArray, threshholds: self.topEdgePortraitWidthThreshholds, measurement: width)
}
class func rowGapPortrait(_ width: CGFloat) -> CGFloat {
return self.findThreshhold(self.rowGapPortraitArray, threshholds: self.rowGapPortraitThreshholds, measurement: width)
}
class func rowGapPortraitLastRow(_ width: CGFloat) -> CGFloat {
let index = self.findThreshholdIndex(self.rowGapPortraitThreshholds, measurement: width)
if index == self.rowGapPortraitLastRowIndex {
return self.rowGapPortraitLastRow
}
else {
return self.rowGapPortraitArray[index]
}
}
class func keyGapPortrait(_ width: CGFloat, rowCharacterCount: Int) -> CGFloat {
let compressed = (rowCharacterCount >= self.keyCompressedThreshhold)
if compressed {
if width >= self.keyGapPortraitUncompressThreshhold {
return self.keyGapPortraitNormal
}
else {
return self.keyGapPortraitSmall
}
}
else {
return self.keyGapPortraitNormal
}
}
class func keyGapLandscape(_ width: CGFloat, rowCharacterCount: Int) -> CGFloat {
let compressed = (rowCharacterCount >= self.keyCompressedThreshhold)
let shrunk = self.keyboardIsShrunk(width)
if compressed || shrunk {
return self.keyGapLandscapeSmall
}
else {
return self.keyGapLandscapeNormal
}
}
class func lastRowKeyGapLandscape(_ width: CGFloat) -> CGFloat {
return self.findThreshhold(self.lastRowKeyGapLandscapeArray, threshholds: self.lastRowKeyGapLandscapeWidthThreshholds, measurement: width)
}
class func keyboardIsShrunk(_ width: CGFloat) -> Bool {
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
return (isPad ? false : width >= self.keyboardShrunkSizeBaseWidthThreshhold)
}
class func keyboardShrunkSize(_ width: CGFloat) -> CGFloat {
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
if isPad {
return width
}
if width >= self.keyboardShrunkSizeBaseWidthThreshhold {
return self.findThreshhold(self.keyboardShrunkSizeArray, threshholds: self.keyboardShrunkSizeWidthThreshholds, measurement: width)
}
else {
return width
}
}
class func popupTotalHeight(_ deviceWidth: CGFloat) -> CGFloat {
return self.findThreshhold(self.popupTotalHeightArray, threshholds: self.popupTotalHeightDeviceWidthThreshholds, measurement: deviceWidth)
}
class func findThreshhold(_ elements: [CGFloat], threshholds: [CGFloat], measurement: CGFloat) -> CGFloat {
assert(elements.count == threshholds.count + 1, "elements and threshholds do not match")
return elements[self.findThreshholdIndex(threshholds, measurement: measurement)]
}
class func findThreshholdIndex(_ threshholds: [CGFloat], measurement: CGFloat) -> Int {
for (i, threshhold) in Array(threshholds.reversed()).enumerated() {
if measurement >= threshhold {
let actualIndex = threshholds.count - i
return actualIndex
}
}
return 0
}
}
class GlobalColors: NSObject {
class var lightModeRegularKey: UIColor { get { return UIColor.white }}
class var darkModeRegularKey: UIColor { get { return UIColor.white.withAlphaComponent(CGFloat(0.3)) }}
class var darkModeSolidColorRegularKey: UIColor { get { return UIColor(red: CGFloat(83)/CGFloat(255), green: CGFloat(83)/CGFloat(255), blue: CGFloat(83)/CGFloat(255), alpha: 1) }}
class var lightModeSpecialKey: UIColor { get { return GlobalColors.lightModeSolidColorSpecialKey }}
class var lightModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(177)/CGFloat(255), green: CGFloat(177)/CGFloat(255), blue: CGFloat(177)/CGFloat(255), alpha: 1) }}
class var lightModeSolidColorSpecialKeyHighlighted: UIColor { get { return UIColor(red: CGFloat(197)/CGFloat(255), green: CGFloat(197)/CGFloat(255), blue: CGFloat(197)/CGFloat(255), alpha: 1) }}
class var darkModeSpecialKey: UIColor { get { return UIColor.gray.withAlphaComponent(CGFloat(0.3)) }}
class var darkModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(45)/CGFloat(255), green: CGFloat(45)/CGFloat(255), blue: CGFloat(45)/CGFloat(255), alpha: 1) }}
class var darkModeSolidColorSpecialKeyHighlighted: UIColor { get { return UIColor(red: CGFloat(65)/CGFloat(255), green: CGFloat(65)/CGFloat(255), blue: CGFloat(65)/CGFloat(255), alpha: 1) }}
class var darkModeShiftKeyDown: UIColor { get { return UIColor(red: CGFloat(214)/CGFloat(255), green: CGFloat(220)/CGFloat(255), blue: CGFloat(208)/CGFloat(255), alpha: 1) }}
class var lightModePopup: UIColor { get { return GlobalColors.lightModeRegularKey }}
class var darkModePopup: UIColor { get { return UIColor.gray }}
class var darkModeSolidColorPopup: UIColor { get { return GlobalColors.darkModeSolidColorRegularKey }}
class var lightModeUnderColor: UIColor { get { return UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1) }}
class var darkModeUnderColor: UIColor { get { return UIColor(red: CGFloat(38.6)/CGFloat(255), green: CGFloat(18)/CGFloat(255), blue: CGFloat(39.3)/CGFloat(255), alpha: 0.4) }}
class var lightModeTextColor: UIColor { get { return UIColor.black }}
class var darkModeTextColor: UIColor { get { return UIColor.white }}
class var lightModeBorderColor: UIColor { get { return UIColor(hue: (214/360.0), saturation: 0.04, brightness: 0.65, alpha: 1.0) }}
class var darkModeBorderColor: UIColor { get { return UIColor.clear }}
class var lightModeSecondaryTextColor: UIColor { get { return UIColor.gray }}
class var darkModeSecondaryTextColor: UIColor { get { return UIColor.gray }}
class func regularKey(_ darkMode: Bool, solidColorMode: Bool) -> UIColor {
if darkMode {
if solidColorMode {
return self.darkModeSolidColorRegularKey
}
else {
return self.darkModeRegularKey
}
}
else {
return self.lightModeRegularKey
}
}
class func popup(_ darkMode: Bool, solidColorMode: Bool) -> UIColor {
if darkMode {
if solidColorMode {
return self.darkModeSolidColorPopup
}
else {
return self.darkModePopup
}
}
else {
return self.lightModePopup
}
}
class func specialKey(_ darkMode: Bool, solidColorMode: Bool) -> UIColor {
if darkMode {
if solidColorMode {
return self.darkModeSolidColorSpecialKey
}
else {
return self.darkModeSpecialKey
}
}
else {
if solidColorMode {
return self.lightModeSolidColorSpecialKey
}
else {
return self.lightModeSpecialKey
}
}
}
class func buttonColor(_ darkMode: Bool) -> UIColor {
if darkMode {
return self.darkModeSolidColorSpecialKeyHighlighted
}
else {
return self.lightModeSolidColorSpecialKeyHighlighted
}
}
}
//"darkShadowColor": UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1),
//"blueColor": UIColor(hue: (211/360.0), saturation: 1.0, brightness: 1.0, alpha: 1),
//"blueShadowColor": UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.43, alpha: 1),
extension CGRect: Hashable {
public var hashValue: Int {
get {
return (origin.x.hashValue ^ origin.y.hashValue ^ size.width.hashValue ^ size.height.hashValue)
}
}
}
extension CGSize: Hashable {
public var hashValue: Int {
get {
return (width.hashValue ^ height.hashValue)
}
}
}
// handles the layout for the keyboard, including key spacing and arrangement
class KeyboardLayout: NSObject, KeyboardKeyProtocol {
class var shouldPoolKeys: Bool { get { return true }}
var layoutConstants: LayoutConstants.Type
var globalColors: GlobalColors.Type
unowned var model: Keyboard
unowned var superview: UIView
var modelToView: [Key:KeyboardKey] = [:]
var viewToModel: [KeyboardKey:Key] = [:]
var keyPool: [KeyboardKey] = []
var nonPooledMap: [String:KeyboardKey] = [:]
var sizeToKeyMap: [CGSize:[KeyboardKey]] = [:]
var shapePool: [String:Shape] = [:]
var darkMode: Bool
var solidColorMode: Bool
var initialized: Bool
required init(model: Keyboard, superview: UIView, layoutConstants: LayoutConstants.Type, globalColors: GlobalColors.Type, darkMode: Bool, solidColorMode: Bool) {
self.layoutConstants = layoutConstants
self.globalColors = globalColors
self.initialized = false
self.model = model
self.superview = superview
self.darkMode = darkMode
self.solidColorMode = solidColorMode
}
// TODO: remove this method
func initialize() {
assert(!self.initialized, "already initialized")
self.initialized = true
}
func viewForKey(_ model: Key) -> KeyboardKey? {
return self.modelToView[model]
}
func keyForView(_ key: KeyboardKey) -> Key? {
return self.viewToModel[key]
}
//////////////////////////////////////////////
// CALL THESE FOR LAYOUT/APPEARANCE CHANGES //
//////////////////////////////////////////////
func layoutKeys(_ pageNum: Int, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) {
CATransaction.begin()
CATransaction.setDisableActions(true)
// pre-allocate all keys if no cache
if !type(of: self).shouldPoolKeys {
if self.keyPool.isEmpty {
for p in 0..<self.model.pages.count {
self.positionKeys(p)
}
self.updateKeyAppearance()
self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState)
}
}
self.positionKeys(pageNum)
// reset state
for (p, page) in self.model.pages.enumerated() {
for (_, row) in page.rows.enumerated() {
for (_, key) in row.enumerated() {
if let keyView = self.modelToView[key] {
keyView.hidePopup()
keyView.isHighlighted = false
keyView.isHidden = (p != pageNum)
}
}
}
}
if type(of: self).shouldPoolKeys {
self.updateKeyAppearance()
self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState)
}
CATransaction.commit()
}
func positionKeys(_ pageNum: Int) {
CATransaction.begin()
CATransaction.setDisableActions(true)
let setupKey = { (view: KeyboardKey, model: Key, frame: CGRect) -> Void in
view.frame = frame
self.modelToView[model] = view
self.viewToModel[view] = model
}
if var keyMap = self.generateKeyFrames(self.model, bounds: self.superview.bounds, page: pageNum) {
if type(of: self).shouldPoolKeys {
self.modelToView.removeAll(keepingCapacity: true)
self.viewToModel.removeAll(keepingCapacity: true)
self.resetKeyPool()
var foundCachedKeys = [Key]()
// pass 1: reuse any keys that match the required size
for (key, frame) in keyMap {
if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) {
foundCachedKeys.append(key)
setupKey(keyView, key, frame)
}
}
foundCachedKeys.map {
keyMap.removeValue(forKey: $0)
}
// pass 2: fill in the blanks
for (key, frame) in keyMap {
let keyView = self.generateKey()
setupKey(keyView, key, frame)
}
}
else {
for (key, frame) in keyMap {
if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) {
setupKey(keyView, key, frame)
}
}
}
}
CATransaction.commit()
}
func updateKeyAppearance() {
CATransaction.begin()
CATransaction.setDisableActions(true)
for (key, view) in self.modelToView {
self.setAppearanceForKey(view, model: key, darkMode: self.darkMode, solidColorMode: self.solidColorMode)
}
CATransaction.commit()
}
// on fullReset, we update the keys with shapes, images, etc. as if from scratch; otherwise, just update the text
// WARNING: if key cache is disabled, DO NOT CALL WITH fullReset MORE THAN ONCE
func updateKeyCaps(_ fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) {
CATransaction.begin()
CATransaction.setDisableActions(true)
if fullReset {
for (_, key) in self.modelToView {
key.shape = nil
if let imageKey = key as? ImageKey { // TODO:
imageKey.image = nil
}
}
}
for (model, key) in self.modelToView {
self.updateKeyCap(key, model: model, fullReset: fullReset, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState)
}
CATransaction.commit()
}
func updateKeyCap(_ key: KeyboardKey, model: Key, fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) {
if fullReset {
// font size
switch model.type {
case
Key.KeyType.modeChange,
Key.KeyType.space,
Key.KeyType.return:
key.label.adjustsFontSizeToFitWidth = true
key.secondaryLabel.adjustsFontSizeToFitWidth = true
key.label.font = key.label.font.withSize(16)
key.secondaryLabel.font = key.secondaryLabel.font.withSize(12)
default:
key.label.font = key.label.font.withSize(22)
key.secondaryLabel.font = key.secondaryLabel.font.withSize(16)
}
// label inset
switch model.type {
case
Key.KeyType.modeChange:
key.labelInset = 3
default:
key.labelInset = 3
}
// shapes
switch model.type {
case Key.KeyType.shift:
if key.shape == nil {
let shiftShape = self.getShape(ShiftShape)
key.shape = shiftShape
}
case Key.KeyType.backspace:
if key.shape == nil {
let backspaceShape = self.getShape(BackspaceShape)
key.shape = backspaceShape
}
case Key.KeyType.keyboardChange:
if key.shape == nil {
let globeShape = self.getShape(GlobeShape)
key.shape = globeShape
}
default:
break
}
// images
if model.type == Key.KeyType.settings {
if let imageKey = key as? ImageKey {
if imageKey.image == nil {
let gearImage = UIImage(named: "gear")
let settingsImageView = UIImageView(image: gearImage)
imageKey.image = settingsImageView
}
}
}
}
if model.type == Key.KeyType.shift {
if key.shape == nil {
let shiftShape = self.getShape(ShiftShape)
key.shape = shiftShape
}
switch shiftState {
case .disabled:
key.isHighlighted = false
case .enabled:
key.isHighlighted = true
case .locked:
key.isHighlighted = true
}
(key.shape as? ShiftShape)?.withLock = (shiftState == .locked)
}
self.updateKeyCapText(key, model: model, uppercase: uppercase, characterUppercase: characterUppercase)
}
func updateKeyCapText(_ key: KeyboardKey, model: Key, uppercase: Bool, characterUppercase: Bool) {
if model.type == .character {
key.text = model.keyCapForCase(characterUppercase)
if model.secondaryOutput != nil {
key.secondaryText = model.secondaryOutput!
}
else {
key.secondaryText = ""
}
}
else {
key.text = model.keyCapForCase(uppercase)
if model.secondaryOutput != nil {
key.secondaryText = model.secondaryOutput!
}
else {
key.secondaryText = ""
}
}
}
///////////////
// END CALLS //
///////////////
func setAppearanceForKey(_ key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) {
if model.type == Key.KeyType.other {
self.setAppearanceForOtherKey(key, model: model, darkMode: darkMode, solidColorMode: solidColorMode)
}
switch model.type {
case
Key.KeyType.character,
Key.KeyType.specialCharacter,
Key.KeyType.period:
key.color = self.self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode)
if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
}
else {
key.downColor = nil
}
key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor)
key.downTextColor = nil
case
Key.KeyType.space:
key.color = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode)
key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor)
key.downTextColor = nil
case
Key.KeyType.shift:
key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
key.downColor = (darkMode ? self.globalColors.darkModeShiftKeyDown : self.globalColors.lightModeRegularKey)
key.textColor = self.globalColors.darkModeTextColor
key.downTextColor = self.globalColors.lightModeTextColor
case
Key.KeyType.tab:
key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
key.downColor = (darkMode ? self.globalColors.darkModeShiftKeyDown : self.globalColors.lightModeRegularKey)
key.textColor = self.globalColors.darkModeTextColor
key.downTextColor = self.globalColors.lightModeTextColor
case
Key.KeyType.backspace:
key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
// TODO: actually a bit different
key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode)
key.textColor = self.globalColors.darkModeTextColor
key.downTextColor = (darkMode ? nil : self.globalColors.lightModeTextColor)
case
Key.KeyType.modeChange:
key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
key.downColor = nil
key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor)
key.downTextColor = nil
case
Key.KeyType.return,
Key.KeyType.keyboardChange,
Key.KeyType.settings:
key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode)
// TODO: actually a bit different
key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode)
key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor)
key.downTextColor = nil
default:
break
}
key.popupColor = self.globalColors.popup(darkMode, solidColorMode: solidColorMode)
key.underColor = (self.darkMode ? self.globalColors.darkModeUnderColor : self.globalColors.lightModeUnderColor)
key.borderColor = (self.darkMode ? self.globalColors.darkModeBorderColor : self.globalColors.lightModeBorderColor)
}
func setAppearanceForOtherKey(_ key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) { /* override this to handle special keys */ }
// TODO: avoid array copies
// TODO: sizes stored not rounded?
///////////////////////////
// KEY POOLING FUNCTIONS //
///////////////////////////
// if pool is disabled, always returns a unique key view for the corresponding key model
func pooledKey(key aKey: Key, model: Keyboard, frame: CGRect) -> KeyboardKey? {
if !type(of: self).shouldPoolKeys {
var p: Int!
var r: Int!
var k: Int!
// TODO: O(N^2) in terms of total # of keys since pooledKey is called for each key, but probably doesn't matter
var foundKey: Bool = false
for (pp, page) in model.pages.enumerated() {
for (rr, row) in page.rows.enumerated() {
for (kk, key) in row.enumerated() {
if key == aKey {
p = pp
r = rr
k = kk
foundKey = true
}
if foundKey {
break
}
}
if foundKey {
break
}
}
if foundKey {
break
}
}
let id = "p\(p)r\(r)k\(k)"
if let key = self.nonPooledMap[id] {
return key
}
else {
let key = generateKey()
self.nonPooledMap[id] = key
return key
}
}
else {
if var keyArray = self.sizeToKeyMap[frame.size] {
if let key = keyArray.last {
if keyArray.count == 1 {
self.sizeToKeyMap.removeValue(forKey: frame.size)
}
else {
keyArray.removeLast()
self.sizeToKeyMap[frame.size] = keyArray
}
return key
}
else {
return nil
}
}
else {
return nil
}
}
}
func createNewKey() -> KeyboardKey {
return ImageKey(vibrancy: nil)
}
// if pool is disabled, always generates a new key
func generateKey() -> KeyboardKey {
let createAndSetupNewKey = { () -> KeyboardKey in
let keyView = self.createNewKey()
keyView.isEnabled = true
keyView.delegate = self
self.superview.addSubview(keyView)
self.keyPool.append(keyView)
return keyView
}
if type(of: self).shouldPoolKeys {
if !self.sizeToKeyMap.isEmpty {
var (size, keyArray) = self.sizeToKeyMap[self.sizeToKeyMap.startIndex]
if let key = keyArray.last {
if keyArray.count == 1 {
self.sizeToKeyMap.removeValue(forKey: size)
}
else {
keyArray.removeLast()
self.sizeToKeyMap[size] = keyArray
}
return key
}
else {
return createAndSetupNewKey()
}
}
else {
return createAndSetupNewKey()
}
}
else {
return createAndSetupNewKey()
}
}
// if pool is disabled, doesn't do anything
func resetKeyPool() {
if type(of: self).shouldPoolKeys {
self.sizeToKeyMap.removeAll(keepingCapacity: true)
for key in self.keyPool {
if var keyArray = self.sizeToKeyMap[key.frame.size] {
keyArray.append(key)
self.sizeToKeyMap[key.frame.size] = keyArray
}
else {
var keyArray = [KeyboardKey]()
keyArray.append(key)
self.sizeToKeyMap[key.frame.size] = keyArray
}
key.isHidden = true
}
}
}
// TODO: no support for more than one of the same shape
// if pool disabled, always returns new shape
func getShape(_ shapeClass: Shape.Type) -> Shape {
let className = NSStringFromClass(shapeClass)
if type(of: self).shouldPoolKeys {
if let shape = self.shapePool[className] {
return shape
}
else {
let shape = shapeClass.init(frame: CGRect.zero)
self.shapePool[className] = shape
return shape
}
}
else {
return shapeClass.init(frame: CGRect.zero)
}
}
//////////////////////
// LAYOUT FUNCTIONS //
//////////////////////
func rounded(_ measurement: CGFloat) -> CGFloat {
return round(measurement * UIScreen.main.scale) / UIScreen.main.scale
}
func generateKeyFrames(_ model: Keyboard, bounds: CGRect, page pageToLayout: Int) -> [Key:CGRect]? {
if bounds.height == 0 || bounds.width == 0 {
return nil
}
var keyMap = [Key:CGRect]()
let isLandscape: Bool = {
let boundsRatio = bounds.width / bounds.height
return (boundsRatio >= self.layoutConstants.landscapeRatio)
}()
var sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(bounds.width))
let bottomEdge = sideEdges
let normalKeyboardSize = bounds.width - CGFloat(2) * sideEdges
let shrunkKeyboardSize = self.layoutConstants.keyboardShrunkSize(normalKeyboardSize)
sideEdges += ((normalKeyboardSize - shrunkKeyboardSize) / CGFloat(2))
let topEdge: CGFloat = (isLandscape ? self.layoutConstants.topEdgeLandscape : self.layoutConstants.topEdgePortrait(bounds.width))
let rowGap: CGFloat = (isLandscape ? self.layoutConstants.rowGapLandscape : self.layoutConstants.rowGapPortrait(bounds.width))
let lastRowGap: CGFloat = (isLandscape ? rowGap : self.layoutConstants.rowGapPortraitLastRow(bounds.width))
//let flexibleEndRowM = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait)
//let flexibleEndRowC = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait)
let lastRowLeftSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth)
let lastRowRightSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth)
let lastRowKeyGap = (isLandscape ? self.layoutConstants.lastRowKeyGapLandscape(bounds.width) : self.layoutConstants.lastRowKeyGapPortrait)
for (p, page) in model.pages.enumerated() {
if p != pageToLayout {
continue
}
let numRows = page.rows.count
let mostKeysInRow = page.maxRowSize()
let rowGapTotal = CGFloat(numRows - 1 - 1) * rowGap + lastRowGap
let keyGap: CGFloat = (isLandscape ? self.layoutConstants.keyGapLandscape(bounds.width, rowCharacterCount: Int(mostKeysInRow)) : self.layoutConstants.keyGapPortrait(bounds.width, rowCharacterCount: Int(mostKeysInRow)))
let keyHeight: CGFloat = {
let totalGaps = bottomEdge + topEdge + rowGapTotal
let returnHeight = (bounds.height - totalGaps) / CGFloat(numRows)
return self.rounded(returnHeight)
}()
let letterKeyWidth: CGFloat = {
let totalGaps = (sideEdges * CGFloat(2)) + (keyGap * CGFloat(mostKeysInRow - 1))
let returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow)
return self.rounded(returnWidth)
}()
let processRow = { (row: [Key], frames: [CGRect], map: inout [Key:CGRect]) -> Void in
assert(row.count == frames.count, "row and frames don't match")
for (k, key) in row.enumerated() {
map[key] = frames[k]
}
}
for (r, row) in page.rows.enumerated() {
let rowGapCurrentTotal = (r == page.rows.count - 1 ? rowGapTotal : CGFloat(r) * rowGap)
let frame = CGRect(x: rounded(sideEdges), y: rounded(topEdge + (CGFloat(r) * keyHeight) + rowGapCurrentTotal), width: rounded(bounds.width - CGFloat(2) * sideEdges), height: rounded(keyHeight))
var frames: [CGRect]!
// basic character row: only typable characters
if self.characterRowHeuristic(row) {
frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame)
}
// character row with side buttons: shift, backspace, etc.
else if self.doubleSidedRowHeuristic(row) {
//frames = self.layoutCharacterWithSidesRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap)
frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame)
}
// bottom row with things like space, return, etc.
else {
frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame)
//frames = self.layoutSpecialKeysRow(row, keyWidth: letterKeyWidth, gapWidth: lastRowKeyGap, leftSideRatio: lastRowLeftSideRatio, rightSideRatio: lastRowRightSideRatio, micButtonRatio: self.layoutConstants.micButtonPortraitWidthRatioToOtherSpecialButtons, isLandscape: isLandscape, frame: frame)
}
processRow(row, frames, &keyMap)
}
}
return keyMap
}
func getRowSize(_ row: [Key]) -> Double {
var sum: Double = 0
for key in row {
sum += key.size!
}
return sum
}
func characterRowHeuristic(_ row: [Key]) -> Bool {
return (row.count >= 1 && row[0].isCharacter)
}
func doubleSidedRowHeuristic(_ row: [Key]) -> Bool {
return (row.count >= 3 && !row[0].isCharacter && row[1].isCharacter)
}
func layoutCharacterRow(_ row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, frame: CGRect) -> [CGRect] {
var frames = [CGRect]()
let rowSize = getRowSize(row)
let keySpace = CGFloat(rowSize) * keyWidth + CGFloat(rowSize - 1) * gapWidth
var actualGapWidth = gapWidth
var sideSpace = (frame.width - keySpace) / CGFloat(2)
// TODO: port this to the other layout functions
// avoiding rounding errors
if sideSpace < 0 {
sideSpace = 0
actualGapWidth = (frame.width - (CGFloat(rowSize) * keyWidth)) / CGFloat(rowSize - 1)
}
var currentOrigin = frame.origin.x
//if first element should not be elongated offset
if row.first?.type == .specialCharacter || row.first?.type == .character {
currentOrigin += sideSpace
}
for (iter, key) in row.enumerated() {
let roundedOrigin = rounded(currentOrigin)
let keySize = keyWidth * CGFloat(key.size!) + actualGapWidth * CGFloat(key.size! - 1)
// avoiding rounding errors
if roundedOrigin + keyWidth > frame.origin.x + frame.width {
frames.append(CGRect(x: rounded(frame.origin.x + frame.width - keyWidth), y: frame.origin.y, width: keyWidth, height: frame.height))
}
else {
//check if first or last element should be elongated
if (iter == 0 || iter == row.count - 1) && (key.type != .specialCharacter && key.type != .character)
{
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: keySize + sideSpace, height: frame.height))
currentOrigin += sideSpace
}
else {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: keySize, height: frame.height))
}
}
currentOrigin += (keySize + actualGapWidth)
}
return frames
}
// TODO: pass in actual widths instead
func layoutCharacterWithSidesRow(_ row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] {
var frames = [CGRect]()
let standardFullKeyCount = Int(self.layoutConstants.keyCompressedThreshhold) - 1
let standardGap = (isLandscape ? self.layoutConstants.keyGapLandscape : self.layoutConstants.keyGapPortrait)(frame.width, standardFullKeyCount)
let sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(frame.width))
var standardKeyWidth = (frame.width - sideEdges - (standardGap * CGFloat(standardFullKeyCount - 1)) - sideEdges)
standardKeyWidth /= CGFloat(standardFullKeyCount)
let standardKeyCount = self.layoutConstants.flexibleEndRowMinimumStandardCharacterWidth
let standardWidth = CGFloat(standardKeyWidth * standardKeyCount + standardGap * (standardKeyCount - 1))
let currentWidth = CGFloat(row.count - 2) * keyWidth + CGFloat(row.count - 3) * keyGap
let isStandardWidth = (currentWidth < standardWidth)
let actualWidth = (isStandardWidth ? standardWidth : currentWidth)
let actualGap = (isStandardWidth ? standardGap : keyGap)
let actualKeyWidth = (actualWidth - CGFloat(row.count - 3) * actualGap) / CGFloat(row.count - 2)
let sideSpace = (frame.width - actualWidth) / CGFloat(2)
let m = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait)
let c = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait)
var specialCharacterWidth = sideSpace * m + c
specialCharacterWidth = max(specialCharacterWidth, keyWidth)
specialCharacterWidth = rounded(specialCharacterWidth)
let specialCharacterGap = sideSpace - specialCharacterWidth
var currentOrigin = frame.origin.x
for (k, key) in row.enumerated() {
if k == 0 {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: specialCharacterWidth, height: frame.height))
currentOrigin += (specialCharacterWidth + specialCharacterGap)
}
else if k == row.count - 1 {
currentOrigin += specialCharacterGap
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: specialCharacterWidth, height: frame.height))
currentOrigin += specialCharacterWidth
}
else {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: actualKeyWidth, height: frame.height))
if k == row.count - 2 {
currentOrigin += (actualKeyWidth)
}
else {
currentOrigin += (actualKeyWidth + keyGap)
}
}
}
return frames
}
func layoutSpecialKeysRow(_ row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, leftSideRatio: CGFloat, rightSideRatio: CGFloat, micButtonRatio: CGFloat, isLandscape: Bool, frame: CGRect) -> [CGRect] {
var frames = [CGRect]()
var keysBeforeSpace = 0
var keysAfterSpace = 0
var reachedSpace = false
for (k, key) in row.enumerated() {
if key.type == Key.KeyType.space {
reachedSpace = true
}
else {
if !reachedSpace {
keysBeforeSpace += 1
}
else {
keysAfterSpace += 1
}
}
}
assert(keysBeforeSpace <= 3, "invalid number of keys before space (only max 3 currently supported)")
assert(keysAfterSpace == 1, "invalid number of keys after space (only default 1 currently supported)")
let hasButtonInMicButtonPosition = (keysBeforeSpace == 3)
var leftSideAreaWidth = frame.width * leftSideRatio
let rightSideAreaWidth = frame.width * rightSideRatio
var leftButtonWidth = (leftSideAreaWidth - (gapWidth * CGFloat(2 - 1))) / CGFloat(2)
leftButtonWidth = rounded(leftButtonWidth)
var rightButtonWidth = (rightSideAreaWidth - (gapWidth * CGFloat(keysAfterSpace - 1))) / CGFloat(keysAfterSpace)
rightButtonWidth = rounded(rightButtonWidth)
let micButtonWidth = (isLandscape ? leftButtonWidth : leftButtonWidth * micButtonRatio)
// special case for mic button
if hasButtonInMicButtonPosition {
leftSideAreaWidth = leftSideAreaWidth + gapWidth + micButtonWidth
}
var spaceWidth = frame.width - leftSideAreaWidth - rightSideAreaWidth - gapWidth * CGFloat(2)
spaceWidth = rounded(spaceWidth)
var currentOrigin = frame.origin.x
var beforeSpace: Bool = true
for (k, key) in row.enumerated() {
if key.type == Key.KeyType.space {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: spaceWidth, height: frame.height))
currentOrigin += (spaceWidth + gapWidth)
beforeSpace = false
}
else if beforeSpace {
if hasButtonInMicButtonPosition && k == 2 { //mic button position
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: micButtonWidth, height: frame.height))
currentOrigin += (micButtonWidth + gapWidth)
}
else {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: leftButtonWidth, height: frame.height))
currentOrigin += (leftButtonWidth + gapWidth)
}
}
else {
frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: rightButtonWidth, height: frame.height))
currentOrigin += (rightButtonWidth + gapWidth)
}
}
return frames
}
////////////////
// END LAYOUT //
////////////////
func frameForPopup(_ key: KeyboardKey, direction: Direction) -> CGRect {
let actualScreenWidth = (UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale)
let totalHeight = self.layoutConstants.popupTotalHeight(actualScreenWidth)
let popupWidth = key.bounds.width + self.layoutConstants.popupWidthIncrement
let popupHeight = CGFloat(50)//totalHeight - key.bounds.height // - self.layoutConstants.popupGap
let popupCenterY = 0
return CGRect(x: (key.bounds.width - popupWidth) / CGFloat(2), y: -popupHeight - self.layoutConstants.popupGap, width: popupWidth, height: popupHeight)
}
func willShowPopup(_ key: KeyboardKey, direction: Direction) {
// TODO: actual numbers, not standins
if let popup = key.popup {
// TODO: total hack
let actualSuperview = (self.superview.superview != nil ? self.superview.superview! : self.superview)
var localFrame = actualSuperview.convert(popup.frame, from: popup.superview)
if localFrame.origin.y < 3 {
localFrame.origin.y = 3
key.background.attached = Direction.down
key.connector?.startDir = Direction.down
key.background.hideDirectionIsOpposite = true
}
else {
// TODO: this needs to be reset somewhere
key.background.hideDirectionIsOpposite = false
}
if localFrame.origin.x < 3 {
localFrame.origin.x = key.frame.origin.x
}
if localFrame.origin.x + localFrame.width > superview.bounds.width - 3 {
localFrame.origin.x = key.frame.origin.x + key.frame.width - localFrame.width
}
popup.frame = actualSuperview.convert(localFrame, to: popup.superview)
}
}
func willHidePopup(_ key: KeyboardKey) {
}
}
| bsd-3-clause | ab0dc7fde25e12a42de94f6ac480499f | 42.410488 | 315 | 0.588811 | 5.290579 | false | false | false | false |
hirohisa/RxSwift | Playgrounds/ObservablesOperators/Observables+Utility.playground/Contents.swift | 3 | 3488 | import Cocoa
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Observable Utility Operators
A toolbox of useful Operators for working with Observables.
### `subscribe`
Create an Disposable which listen events from source Observable, the given closure take the Even and is responsible for the actions to perform when the it is produced.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/subscribe.html )
*/
example("subscribe") {
let intOb1 = PublishSubject<Int>()
intOb1
>- subscribe { event in
println(event)
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
/*:
There are several variants of the `subscribe` operator. They works over one posible event type:
### `subscribeNext`
Create an Disposable which listen only Next event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Next even is produced.
*/
example("subscribeNext") {
let intOb1 = PublishSubject<Int>()
intOb1
>- subscribeNext { int in
println(int)
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
/*:
### `subscribeCompleted`
Create an Disposable which listen only Completed event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Completed even is produced.
*/
example("subscribeCompleted") {
let intOb1 = PublishSubject<Int>()
intOb1
>- subscribeCompleted {
println("It's completed")
}
sendNext(intOb1, 1)
sendCompleted(intOb1)
}
/*:
### `subscribeError
Create an Disposable which listen only Error event from source Observable, the given closure take the Even's value and is responsible for the actions to perform only when the Error even is produced
*/
example("subscribeError") {
let intOb1 = PublishSubject<Int>()
intOb1
>- subscribeError { error in
println(error)
}
sendNext(intOb1, 1)
sendError(intOb1, NSError(domain: "Examples", code: -1, userInfo: nil))
}
/*:
### `do`
Returns the same source Observable but the given closure responsible for the actions to perform when the even is produced. The gived closure obtain the event produced by the source observable
[More info in reactive.io website]( http://reactivex.io/documentation/operators/do.html )
*/
example("do") {
let intOb1 = PublishSubject<Int>()
let intOb2 = intOb1
>- `do` { event in
println("first \(event)")
}
intOb2
>- subscribeNext { int in
println("second \(int)")
}
sendNext(intOb1, 1)
}
/*:
### `doOnNext`
It is a variant of the `do` operator. Returns the same source Observable but the given closure responsible for the actions to perform when the Next even is produced. The gived closure obtain the value of the Next event produced by the source observable.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/do.html )
*/
example("doOnNext") {
let intOb1 = PublishSubject<Int>()
let intOb2 = intOb1
>- doOnNext { int in
println("first \(int)")
}
intOb2
>- subscribeNext { int in
println("second \(int)")
}
sendNext(intOb1, 1)
}
| mit | 26a15781921215dfb6b2c88f4991324a | 23.56338 | 253 | 0.669725 | 4.365457 | false | false | false | false |
yylai/Flicklicious | Flicks/DetailViewController.swift | 1 | 3174 | //
// DetailViewController.swift
// Flicks
//
// Created by YINYEE LAI on 10/16/16.
// Copyright © 2016 Yin Yee Lai. All rights reserved.
//
import UIKit
import AFNetworking
class DetailViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var infoView: UIView!
var movie: NSDictionary!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: infoView.frame.origin.y + infoView.frame.size.height)
let title = movie["title"] as! String
let overview = movie["overview"] as! String
titleLabel.text = title
overviewLabel.text = overview
overviewLabel.sizeToFit()
if let posterURL = movie["poster_path"] as? String {
//let baseURL = "https://image.tmdb.org/t/p/w500"
let lowImgBaseURL = "https://image.tmdb.org/t/p/w45"
let origImgBaseURL = "https://image.tmdb.org/t/p/original"
let lowImgURL = URL(string: lowImgBaseURL + posterURL)
let origImgURL = URL(string: origImgBaseURL + posterURL)
let lowImgReq = URLRequest(url: lowImgURL!)
let origImgReq = URLRequest(url: origImgURL!)
posterImageView.setImageWith(lowImgReq, placeholderImage: nil, success: { (req, resp, lowImg) in
if let response = resp {
self.posterImageView.alpha = 0
self.posterImageView.image = lowImg
UIView.animate(withDuration: 0.3, animations: {
self.posterImageView.alpha = 1
}, completion: { (success) in
self.posterImageView.setImageWith(origImgReq, placeholderImage: lowImg, success: { (origReq, origResp, origImg) in
self.posterImageView.image = origImg
}, failure: { (origReq, origResp, origError) in
self.posterImageView.image = lowImg
})
})
} else {
self.posterImageView.image = lowImg
}
}, failure: { (req, resp, err) in
self.posterImageView.image = nil
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 7a922e1cce3e625c29e0a42c9159302e | 33.11828 | 138 | 0.56382 | 4.942368 | false | false | false | false |
fsiu/SprityBirdInSwift | SprityBirdInSwift/src/Helpers/Math.swift | 1 | 676 | //
// Math.swift
// SprityBirdInSwift
//
// Created by Frederick Siu on 6/6/14.
// Copyright (c) 2014 Frederick Siu. All rights reserved.
//
import Foundation
struct Math {
static var seed: UInt32 = 0
// func setRandomSeed(_ seed: UInt32) {
// Math.seed = seed;
// arc4random(seed)
// }
func randomFloatBetween(_ min: Float, max: Float) -> Float {
let randMaxNumerator = Float(arc4random_uniform(UInt32(RAND_MAX)))//Float(arc4random() % RAND_MAX)
let randMaxDivisor = Float(RAND_MAX) * 1.0
let random: Float = Float((randMaxNumerator / randMaxDivisor) * (max-min)) + Float(min)
return random
}
}
| apache-2.0 | 8be2d85ad5113d693680c1c23fa6c794 | 26.04 | 106 | 0.621302 | 3.23445 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_2_fixed/0020-rdar21598514.swift | 4 | 5657 | // RUN: not %target-swift-frontend %s -parse
protocol Resettable : AnyObject {
func reset()
}
internal var _allResettables: [Resettable] = []
public class TypeIndexed<Value> : Resettable {
public init(_ value: Value) {
self.defaultValue = value
_allResettables.append(self)
}
public subscript(t: Any.Type) -> Value {
get {
return byType[ObjectIdentifier(t)] ?? defaultValue
}
set {
byType[ObjectIdentifier(t)] = newValue
}
}
public func reset() { byType = [:] }
internal var byType: [ObjectIdentifier:Value] = [:]
internal var defaultValue: Value
}
public protocol Wrapper {
typealias Base
init(_: Base)
var base: Base {get set}
}
public protocol LoggingType : Wrapper {
typealias Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return self.dynamicType
}
}
public class IteratorLog {
public static func dispatchTester<G : IteratorProtocol>(
g: G
) -> LoggingIterator<LoggingIterator<G>> {
return LoggingIterator(LoggingIterator(g))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base : IteratorProtocol>
: IteratorProtocol, LoggingType {
typealias Log = IteratorLog
public init(_ base: Base) {
self.base = base
}
public mutating func next() -> Base.Element? {
++Log.next[selfType]
return base.next()
}
public var base: Base
}
public class SequenceLog {
public class func dispatchTester<S: Sequence>(
s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(LoggingSequence(s))
}
public static var iterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var map = TypeIndexed(0)
public static var filter = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _preprocessingPass = TypeIndexed(0)
public static var _copyToNativeArrayBuffer = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
}
public protocol LoggingSequenceType : Sequence, LoggingType {
typealias Base : Sequence
}
extension LoggingSequenceType {
public init(_ base: Base) {
self.base = base
}
public func makeIterator() -> LoggingIterator<Base.Iterator> {
++SequenceLog.iterator[selfType]
return LoggingIterator(base.makeIterator())
}
public func underestimatedCount() -> Int {
++SequenceLog.underestimatedCount[selfType]
return base.underestimatedCount()
}
public func map<T>(
transform: (Base.Iterator.Element) -> T
) -> [T] {
++SequenceLog.map[selfType]
return base.map(transform)
}
public func filter(
isIncluded: (Base.Iterator.Element) -> Bool
) -> [Base.Iterator.Element] {
++SequenceLog.filter[selfType]
return base.filter(isIncluded)
}
public func _customContainsEquatableElement(
element: Base.Iterator.Element
) -> Bool? {
++SequenceLog._customContainsEquatableElement[selfType]
return base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(
_ preprocess: (Self) -> R
) -> R? {
++SequenceLog._preprocessingPass[selfType]
return base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
++SequenceLog._copyToNativeArrayBuffer[selfType]
return base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) {
++SequenceLog._copyContents[selfType]
return base._copyContents(initializing: ptr)
}
}
public struct LoggingSequence<Base_: Sequence> : LoggingSequenceType {
typealias Log = SequenceLog
typealias Base = Base_
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public class CollectionLog : SequenceLog {
public class func dispatchTester<C: Collection>(
c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(LoggingCollection(c))
}
static var subscriptIndex = TypeIndexed(0)
static var subscriptRange = TypeIndexed(0)
static var isEmpty = TypeIndexed(0)
static var count = TypeIndexed(0)
static var _customIndexOfEquatableElement = TypeIndexed(0)
static var first = TypeIndexed(0)
}
public protocol LoggingCollectionType : Collection, LoggingSequenceType {
typealias Base : Collection
}
extension LoggingCollectionType {
subscript(position: Base.Index) -> Base.Iterator.Element {
++CollectionLog.subscriptIndex[selfType]
return base[position]
}
subscript(_prext_bounds: Range<Base.Index>) -> Base._prext_SubSequence {
++CollectionLog.subscriptRange[selfType]
return base[_prext_bounds]
}
var isEmpty: Bool {
++CollectionLog.isEmpty[selfType]
return base.isEmpty
}
var count: Base.Index.Distance {
++CollectionLog.count[selfType]
return base.count
}
func _customIndexOfEquatableElement(element: Iterator.Element) -> Base.Index?? {
++CollectionLog._customIndexOfEquatableElement[selfType]
return base._customIndexOfEquatableElement(element)
}
var first: Iterator.Element? {
++CollectionLog.first[selfType]
return base.first
}
}
struct LoggingCollection<Base_: Collection> : LoggingCollectionType {}
| apache-2.0 | f6655268e740ee9eefdd4b37c3146c5a | 24.713636 | 82 | 0.70426 | 4.311738 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/CoreDataStoreTransaction.swift | 1 | 8654 | import CoreData
import Foundation
class CoreDataStoreTransaction: DataStoreTransaction {
// MARK: Properties
private var mutations = [(NSManagedObjectContext) -> Void]()
// MARK: Functions
func performMutations(context: NSManagedObjectContext) {
context.performAndWait {
mutations.forEach { $0(context) }
}
}
// MARK: DataStoreTransaction
func saveLastRefreshDate(_ lastRefreshDate: Date) {
mutations.append { (context) in
let fetchRequestForExistingRefreshDate: NSFetchRequest<LastRefreshEntity> = LastRefreshEntity.fetchRequest()
do {
let existingEntities = try fetchRequestForExistingRefreshDate.execute()
existingEntities.forEach(context.delete)
} catch {
print(error)
}
let entity = LastRefreshEntity(context: context)
entity.lastRefreshDate = lastRefreshDate
}
}
func saveKnowledgeGroups(_ knowledgeGroups: [KnowledgeGroupCharacteristics]) {
updateEntities(ofKind: KnowledgeGroupEntity.self, using: knowledgeGroups)
}
func saveKnowledgeEntries(_ knowledgeEntries: [KnowledgeEntryCharacteristics]) {
mutations.append { (context) in
for entry in knowledgeEntries {
let predicate = KnowledgeEntryEntity.makeIdentifyingPredicate(for: entry)
let entity: KnowledgeEntryEntity = context.makeEntity(uniquelyIdentifiedBy: predicate)
entity.links.map(entity.removeFromLinks)
let links = entry.links.map { (link) -> LinkEntity in
let namePredicate = NSPredicate(format: "\(#keyPath(LinkEntity.name)) == %@", link.name)
let targetPredicate = NSPredicate(format: "\(#keyPath(LinkEntity.target)) == %@", link.target)
let fragmentPredicate = NSPredicate(
format: "\(#keyPath(LinkEntity.fragmentType)) == %li",
link.fragmentType.rawValue
)
let predicate = NSCompoundPredicate(
andPredicateWithSubpredicates: [namePredicate, targetPredicate, fragmentPredicate]
)
let entity: LinkEntity = context.makeEntity(uniquelyIdentifiedBy: predicate)
entity.consumeAttributes(from: link)
return entity
}
entity.consumeAttributes(from: entry)
links.forEach(entity.addToLinks)
}
}
}
func saveAnnouncements(_ announcements: [AnnouncementCharacteristics]) {
updateEntities(ofKind: AnnouncementEntity.self, using: announcements)
}
func saveEvents(_ events: [EventCharacteristics]) {
updateEntities(ofKind: EventEntity.self, using: events)
}
func saveRooms(_ rooms: [RoomCharacteristics]) {
updateEntities(ofKind: RoomEntity.self, using: rooms)
}
func saveTracks(_ tracks: [TrackCharacteristics]) {
updateEntities(ofKind: TrackEntity.self, using: tracks)
}
func saveConferenceDays(_ conferenceDays: [ConferenceDayCharacteristics]) {
updateEntities(ofKind: ConferenceDayEntity.self, using: conferenceDays)
}
func saveFavouriteEventIdentifier(_ identifier: EventIdentifier) {
updateEntities(ofKind: FavouriteEventEntity.self, using: [identifier])
}
func saveDealers(_ dealers: [DealerCharacteristics]) {
mutations.append { (context) in
for dealer in dealers {
let predicate = DealerEntity.makeIdentifyingPredicate(for: dealer)
let entity: DealerEntity = context.makeEntity(uniquelyIdentifiedBy: predicate)
entity.consumeAttributes(from: dealer)
let links = dealer.links?.map { (link) -> LinkEntity in
let namePredicate = NSPredicate(format: "\(#keyPath(LinkEntity.name)) == %@", link.name)
let targetPredicate = NSPredicate(format: "\(#keyPath(LinkEntity.target)) == %@", link.target)
let fragmentPredicate = NSPredicate(
format: "\(#keyPath(LinkEntity.fragmentType)) == %li",
link.fragmentType.rawValue
)
let predicate = NSCompoundPredicate(
andPredicateWithSubpredicates: [namePredicate, targetPredicate, fragmentPredicate]
)
let entity: LinkEntity = context.makeEntity(uniquelyIdentifiedBy: predicate)
entity.consumeAttributes(from: link)
return entity
}
links?.forEach(entity.addToLinks)
}
}
}
func saveMaps(_ maps: [MapCharacteristics]) {
mutations.append { (context) in
for map in maps {
let predicate = MapEntity.makeIdentifyingPredicate(for: map)
let entity: MapEntity = context.makeEntity(uniquelyIdentifiedBy: predicate)
entity.consumeAttributes(from: map)
entity.entries.map(entity.removeFromEntries)
let entries = map.entries.map { (entry) -> MapEntryEntity in
let links = entry.links.map { (link) -> MapEntryLinkEntity in
let entity = MapEntryLinkEntity(context: context)
entity.consumeAttributes(from: link)
return entity
}
let entity = MapEntryEntity(context: context)
entity.consumeAttributes(from: entry)
links.forEach(entity.addToLinks)
return entity
}
entries.forEach(entity.addToEntries)
}
}
}
func saveReadAnnouncements(_ announcements: [AnnouncementIdentifier]) {
updateEntities(ofKind: ReadAnnouncementEntity.self, using: announcements)
}
func saveImages(_ images: [ImageCharacteristics]) {
updateEntities(ofKind: ImageModelEntity.self, using: images)
}
func deleteFavouriteEventIdentifier(_ identifier: EventIdentifier) {
deleteFirst(FavouriteEventEntity.self, identifierKey: "eventIdentifier", identifier: identifier.rawValue)
}
func deleteKnowledgeGroup(identifier: String) {
deleteFirst(KnowledgeGroupEntity.self, identifier: identifier)
}
func deleteKnowledgeEntry(identifier: String) {
deleteFirst(KnowledgeEntryEntity.self, identifier: identifier)
}
func deleteAnnouncement(identifier: String) {
deleteFirst(AnnouncementEntity.self, identifier: identifier)
}
func deleteEvent(identifier: String) {
deleteFirst(EventEntity.self, identifier: identifier)
}
func deleteTrack(identifier: String) {
deleteFirst(TrackEntity.self, identifier: identifier)
}
func deleteRoom(identifier: String) {
deleteFirst(RoomEntity.self, identifier: identifier)
}
func deleteConferenceDay(identifier: String) {
deleteFirst(ConferenceDayEntity.self, identifier: identifier)
}
func deleteDealer(identifier: String) {
deleteFirst(DealerEntity.self, identifier: identifier)
}
func deleteMap(identifier: String) {
deleteFirst(MapEntity.self, identifier: identifier)
}
func deleteImage(identifier: String) {
deleteFirst(ImageModelEntity.self, identifier: identifier)
}
// MARK: Private
private func updateEntities<E: NSManagedObject & EntityAdapting>(
ofKind entityType: E.Type,
using models: [E.AdaptedType]
) {
mutations.append { (context) in
models.forEach { (model) in
let entity: E = context.makeEntity(uniquelyIdentifiedBy: E.makeIdentifyingPredicate(for: model))
entity.consumeAttributes(from: model)
}
}
}
private func deleteFirst<T>(
_ kind: T.Type,
identifierKey: String = "identifier",
identifier: String
) where T: NSManagedObject {
mutations.append { (context) in
let fetchRequest = NSFetchRequest<T>(entityName: String(describing: T.self))
fetchRequest.predicate = NSPredicate(format: "\(identifierKey) == %@", identifier)
fetchRequest.fetchLimit = 1
context.deleteFirstMatch(for: fetchRequest)
}
}
}
| mit | 4745af6d6d698f79ea6d03758b949d81 | 36.301724 | 120 | 0.610122 | 5.322263 | false | false | false | false |
CulturaMobile/culturamobile-api | Sources/App/Models/Event.swift | 1 | 4488 | import Vapor
import FluentProvider
import AuthProvider
import HTTP
final class Event: Model {
fileprivate static let databaseTableName = "events"
static var entity = "events"
let storage = Storage()
static let idKey = "id"
static let foreignIdKey = "event_id"
var franchise: Identifier?
var title: String
var description: String
var priceTier: Double
var venue: Identifier?
var phone: String
var cellphone: String
init(franchise: Franchise, title: String, description: String, priceTier: Double, venue: Venue, phone: String, cellphone: String) {
self.franchise = franchise.id
self.title = title
self.description = description
self.priceTier = priceTier
self.venue = venue.id
self.phone = phone
self.cellphone = cellphone
}
// MARK: Row
/// Initializes from the database row
init(row: Row) throws {
franchise = try row.get("franchise_id")
title = try row.get("title")
description = try row.get("description")
priceTier = try row.get("price_tier")
venue = try row.get("venue_id")
phone = try row.get("phone")
cellphone = try row.get("cellphone")
}
// Serializes object to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("franchise_id", franchise)
try row.set("title", title)
try row.set("description", description)
try row.set("price_tier", priceTier)
try row.set("venue_id", venue)
try row.set("phone", phone)
try row.set("cellphone", cellphone)
return row
}
}
// MARK: Preparation
extension Event: Preparation {
/// Prepares a table/collection in the database for storing objects
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.int("franchise_id")
builder.string("title")
builder.custom("description", type: "TEXT")
builder.double("price_tier")
builder.int("venue_id")
builder.string("phone", optional: true)
builder.string("cellphone", optional: true)
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
//
extension Event: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
franchise: json.get("francise_id"),
title: json.get("title"),
description: json.get("description"),
priceTier: json.get("price_tier"),
venue: json.get("venue_id"),
phone: json.get("phone"),
cellphone: json.get("cellphone")
)
id = try json.get("id")
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("title", title)
try json.set("description", description)
try json.set("price_tier", priceTier)
let currentVenue = try Venue.find(venue)?.makeJSON()
try json.set("venue", currentVenue)
try json.set("phone", phone)
try json.set("cellphone", cellphone)
let categories = try EventCategory.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("categories", categories)
let comments = try EventComment.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("comments", comments)
let dates = try EventDate.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("dates", dates)
let images = try EventImage.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("images", images)
let tags = try EventTag.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("tags", tags)
let guestList = try EventGuestList.makeQuery().filter("event_id", self.id).all().makeJSON()
try json.set("guest_list", guestList)
return json
}
}
// MARK: HTTP
// This allows User models to be returned
// directly in route closures
extension Event: ResponseRepresentable { }
extension Event: Timestampable {
static var updatedAtKey: String { return "updated_at" }
static var createdAtKey: String { return "created_at" }
}
| mit | 21081074e3dc161737af60e406db0313 | 30.829787 | 135 | 0.606952 | 4.178771 | false | false | false | false |
Czajnikowski/TrainTrippin | TrainTrippin/DeparturesViewModel.swift | 1 | 5331 | //
// DeparturesViewModel.swift
// TrainTrippin
//
// Created by Maciek on 19.10.2016.
// Copyright © 2016 Fortunity. All rights reserved.
//
import Foundation
import RxDataSources
import RxCocoa
import SWXMLHash
import RxSwift
typealias DeparturesListSection = SectionModel<Void, DepartureCellModelType>
class DeparturesViewModel: NSObject {
// Input:
let refreshDepartures = PublishSubject<Void>()
let toggleRoute = PublishSubject<Void>()
// Output:
let departuresSections: Driver<[DeparturesListSection]>
let showRefreshControl: Observable<Bool>
let currentRoute: Observable<Route>
enum Route {
case fromDalkeyToBroombridge
case fromBroombridgeToDalkey
}
private let _networking = Networking()
private let _departures = Variable<[DepartureModel]>([])
private let _showRefreshControl = PublishSubject<Bool>()
private let _currentRoute = Variable(Route.fromDalkeyToBroombridge)
private let disposeBag = DisposeBag()
override init() {
departuresSections = _departures.asObservable()
.map { departures in
let cellModels = departures.map(DepartureCellModel.init)
let section = DeparturesListSection(model: Void(), items: cellModels)
return [section]
}
.asDriver(onErrorJustReturn: [])
Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.withLatestFrom(_departures.asObservable())
.asDriver(onErrorJustReturn: [])
.drive(_departures)
.addDisposableTo(disposeBag)
showRefreshControl = _showRefreshControl.asObservable()
currentRoute = _currentRoute.asObservable()
super.init()
toggleRoute
.subscribe(onNext: { [unowned self] _ in
if self._currentRoute.value == Route.fromBroombridgeToDalkey {
self._currentRoute.value = Route.fromDalkeyToBroombridge
}
else {
self._currentRoute.value = Route.fromBroombridgeToDalkey
}
})
.addDisposableTo(disposeBag)
refreshDepartures
.withLatestFrom(currentRoute.asObservable())
.subscribe(onNext: { [unowned self] route in
let request: Observable<XMLIndexer>
if route == Route.fromDalkeyToBroombridge {
request = self._networking.requestTrainsFromDalkey()
}
else {
request = self._networking.requestTrainsFromBroombridge()
}
request
.do(onNext: { response in
self._showRefreshControl.onNext(false)
}, onError: { _ in
self._showRefreshControl.onNext(false)
})
.map(self.transformResponseIntoDepartureModelsTowardsDestination)
.bindTo(self._departures)
.addDisposableTo(self.disposeBag)
}
)
.addDisposableTo(disposeBag)
currentRoute
.skip(1)
.distinctUntilChanged(==)
.map { _ in
return Void()
}
.bindTo(refreshDepartures)
.addDisposableTo(disposeBag)
}
func viewModel(forIndexPath indexPath: IndexPath) -> RouteViewModel {
let model = _departures.value[indexPath.row]
return RouteViewModel(withDepartureModel: model)
}
struct XMLElementName {
static let root = "ArrayOfObjStationData"
static let stationData = "objStationData"
static let trainCode = "Traincode"
static let trainType = "Traintype"
static let station = "Stationfullname"
static let expectedDeparture = "Expdepart"
static let trainDirection = "Direction"
static let northboundDirection = "Northbound"
static let southboundDirection = "Southbound"
}
func transformResponseIntoDepartureModelsTowardsDestination(_ xml: XMLIndexer) -> [DepartureModel] {
let station = xml[XMLElementName.root][XMLElementName.stationData]
return station
.map { xml in
let trainCode = xml[XMLElementName.trainCode].element!.text!
let trainType = xml[XMLElementName.trainType].element!.text!
let station = xml[XMLElementName.station].element!.text!
let expectedDeparture = xml[XMLElementName.expectedDeparture].element!.text!
let trainDirection = xml[XMLElementName.trainDirection].element!.text! == XMLElementName.northboundDirection ? TrainDirection.northbound : TrainDirection.southbound
return (trainCode, trainType, expectedDeparture, trainDirection, station)
}
.filter { train in
if _currentRoute.value == .fromDalkeyToBroombridge {
return train.3 == .northbound
}
else {
return train.3 == .southbound
}
}
.map(DepartureModel.init)
}
}
| mit | 0342fdb761126c6438f9e4b349de4d2a | 36.013889 | 180 | 0.589493 | 5.308765 | false | false | false | false |
mrdekk/DataKernel | DataKernel/Classes/Contracts/Request.swift | 1 | 1793 | //
// Request.swift
// DataKernel
//
// Created by Denis Malykh on 30/04/16.
// Copyright © 2016 mrdekk. All rights reserved.
//
import Foundation
public struct Request<E: Entity> {
// MARK: - Props
public let sort: NSSortDescriptor?
public let predicate: NSPredicate?
// MARK: - Init
public init(sort: NSSortDescriptor? = nil, predicate: NSPredicate? = nil) {
self.sort = sort
self.predicate = predicate
}
// MARK: - Chaining specification methods
public func filtered(_ key: String, equalTo value: Any) -> Request<E> {
return self.redef(predicate: NSPredicate(format: "\(key) == %@", argumentArray: [value]))
}
public func filtered(_ key: String, oneOf value: [Any]) -> Request<E> {
return self.redef(predicate: NSPredicate(format: "\(key) IN %@", argumentArray: [value]))
}
public func sorted(_ key: String?, ascending: Bool) -> Request<E> {
return self.redef(sort: NSSortDescriptor(key: key, ascending: ascending))
}
public func sorted(_ key: String?, ascending: Bool, comparator cmptr: @escaping Comparator) -> Request<E> {
return self.redef(sort: NSSortDescriptor(key: key, ascending: ascending, comparator: cmptr))
}
public func sorted(_ key: String?, ascending: Bool, selector: Selector) -> Request<E> {
return self.redef(sort: NSSortDescriptor(key: key, ascending: ascending, selector: selector))
}
// MARK: - Internal
func redef(predicate: NSPredicate) -> Request<E> {
return Request<E>(sort: self.sort, predicate: predicate)
}
func redef(sort: NSSortDescriptor) -> Request<E> {
return Request<E>(sort: sort, predicate: self.predicate)
}
}
| mit | 25c025df1dc418eba08280faa3fecd87 | 29.372881 | 111 | 0.623884 | 4.110092 | false | false | false | false |
u10int/Kinetic | Example/Tests/TimelineTests.swift | 1 | 1477 | //
// TimelineTests.swift
// Kinetic
//
// Created by Nicholas Shipes on 7/29/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
import Nimble
import Kinetic
class TimelineTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTotalDuration() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0))
let timeline = Timeline()
expect(timeline.totalDuration).to(equal(0))
let moveX = Tween(target: view).to(X(110)).duration(0.5)
let moveY = Tween(target: view).to(Y(250)).duration(0.5)
let resize = Tween(target: view).to(Size(width: 200)).duration(0.5)
timeline.add(moveX)
expect(timeline.totalDuration).to(equal(0.5))
timeline.add(moveY, position: 0.25)
expect(timeline.totalDuration).to(equal(0.75))
timeline.add(resize, position: "+=1.5")
expect(timeline.totalDuration).to(equal(2.75))
expect(timeline.children).to(haveCount(3))
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit | a130a2cae1cd8b5a61e7c10b27ca8c47 | 26.333333 | 111 | 0.644986 | 3.626536 | false | true | false | false |
MichaelJordanYang/JDYangDouYuZB | JDYDouYuZb/JDYDouYuZb/Application/Classes/Main/View/PageTitleView.swift | 1 | 4802 | //
// PageTitleView.swift
// JDYDouYuZb
//
// Created by xiaoyang on 2016/12/29.
// Copyright © 2016年 JDYang. All rights reserved.
// 封装标题的view PageTitleView
import UIKit
//确定滚动条的高度
fileprivate let kscrollLineH : CGFloat = 2
class PageTitleView: UIView {
// MARK:- 定义数组属性
fileprivate var titles : [String]
// MARK:- 懒加载属性标题数组UILabel
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
// MARK:- 懒加载属性创建scrollView
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false //水平指示线条不显示
scrollView.scrollsToTop = false //状态栏点击回到最顶部需要设置false属性
//scrollView.isPagingEnabled = false //设置分页
scrollView.bounces = false//设置滚动不超过内容的范围
return scrollView
}()
// MARK:- 懒加载属性创建scrollLine滚动的线
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.purple
return scrollLine
}()
// MARK:- 自定义构造函数
init(frame: CGRect, titles : [String]) {
self.titles = titles //把所有传进来的标题用这个titles属性保存起来
super.init(frame: frame)
// 设置UI界面
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: -设置UI界面
extension PageTitleView {
fileprivate func setUpUI() {
//1.添加UIScrollview
addSubview(scrollView)
scrollView.frame = bounds //设置scrollView的fame等于当前view的bounds
//2.添加title对应的Label
setUpTitleLabels()
//3.设置底部的线条和滚动的滑块
setUpBottomMenuAndScrollLine()
}
// MARK:- 添加title对应的Label
fileprivate func setUpTitleLabels() {
//0.确定UILabel的值因为Label不需要再for里面每次都遍历
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kscrollLineH
//let labelX : CGFloat = labelW * CGFloat(index) //X是多少是根据宽度决定,所以先设置宽度
let labelY : CGFloat = 0
//根据有多少个标题就创建多少个label
for (index, title) in titles.enumerated(){ //通过这种方式创建既可以拿到下标也可以拿到titles
//1.创建UILabel 因为每个标题都对应着lable,在每次遍历的时候都创建label
let label = UILabel()
//2.设置label的属性
label.text = title //名字就对应着title
label.tag = index //给label设置tag, 想拿到label对应的下标的话就拿到tag
label.font = UIFont.systemFont(ofSize: 16.0)//设置字体大小
label.textColor = UIColor.darkGray //设置文字颜色
label.textAlignment = .center //设置为居中
//3.设置label的frame
//let labelW : CGFloat = frame.width / CGFloat(titles.count)
//let labelH : CGFloat = frame.height - kscrollLineH
let labelX : CGFloat = labelW * CGFloat(index) //X是多少是根据宽度决定,所以先设置宽度
//let labelY : CGFloat = 0
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//4.将label添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label) //拿到titleLabels数组将创建的label加入到数组中
}
}
// MARK:- 设置底部的线条和滚动的滑块
fileprivate func setUpBottomMenuAndScrollLine() {
//1.添加底部的线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.orange
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height, width: frame.width, height: lineH)
//scrollView.addSubview(bottomLine)
addSubview(bottomLine)
//2.添加scrollLine滚动的线
//2.1获取第一个label
guard let firstLabel = titleLabels.first else { return } //titleLabels.first是可选类型必须用guard做一个校验
firstLabel.textColor = UIColor.purple
//2.2设置scorollLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kscrollLineH, width: firstLabel.frame.width, height: kscrollLineH)
}
}
| mit | 2d0b571390c696b7f3b64c189fc9d472 | 30.88189 | 148 | 0.620153 | 4.262105 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Views/Custom/ORLoginLabel.swift | 1 | 1451 | //
// ORLoginLabel.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 29/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class ORLoginLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
textAlignment = .center
textColor = UIColor.RGBA(249, 212, 226, 1)
font = UIFont.systemFont(ofSize: 11, weight: UIFontWeightMedium)
text = Localized("ORLoginLabel.OR", comment: "Visible as a text allowing user to choose login method.")
}
@available(*, unavailable, message: "Use init(frame:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let boundingTextRect = text?.boundingRectWithFont(font!, constrainedToWidth: rect.width) ??
CGRect.zero
let space = CGFloat(10)
let y = rect.midY
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(textColor!.cgColor)
context?.setLineWidth(1)
context?.move(to: CGPoint(x: 0, y: y))
context?.addLine(to: CGPoint(x: rect.midX - boundingTextRect.width * 0.5 - space, y: y))
context?.move(to: CGPoint(x: rect.midX + boundingTextRect.width * 0.5 + space, y: y))
context?.addLine(to: CGPoint(x: rect.maxX, y: y))
context?.strokePath()
}
}
| gpl-3.0 | ea29ac2c336d755d53b26c5a11207325 | 29.208333 | 111 | 0.631034 | 3.929539 | false | false | false | false |
jithinpala/JBDropDownMenu | JBDropDownMenu/JBDropDownList.swift | 1 | 9075 | //
// JBDropDownList.swift
// TutorSwift
//
// Created by Developer on 18/03/15.
// Copyright (c) 2015 [email protected]. All rights reserved.
//
import UIKit
protocol JBDropDownDelegate {
func DropDownListViewDataList(datalist: NSMutableArray)
func DropDownListViewDidSelect(didSelectedIndex:NSInteger)
//func DropDownListViewDidSelect(didSelectedIndex:NSInteger)
//func DropDownListViewDidCancel()
}
class JBDropDownList: UIView, UITableViewDataSource, UITableViewDelegate {
let DROPDOWNVIEW_SCREENINSET = 0
let DROPDOWNVIEW_HEADER_HEIGHT = 50
let RADIUS = 5.0
var DropTableView: UITableView = UITableView()
var _kTitleText: NSString!
var _kDropDownOption: NSArray!
var R,G,B,A: CGFloat!
var isMultipleSelection: Bool = false
var jbDelegate: JBDropDownDelegate?
var arryData: NSMutableArray!
var DropDownOption: NSArray!
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
//self.callFingerTapToExit()
}
convenience init(content: String, sender: String, frame: CGRect)
{
//Rule 2 and 3: Calling the Designated Initializer in same class
self.init(frame:frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func callInitialSetup(titleText: NSString, listValues: NSArray, isMultiple: Bool) {
self.backgroundColor = UIColor.clearColor()
isMultipleSelection = isMultiple
_kTitleText = titleText.copy() as NSString
DropDownOption = listValues.copy() as NSArray
arryData = NSMutableArray()
var innerContainer = UIView(frame: self.calculateDropdownContainerSize(listValues.count))
innerContainer.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
innerContainer.layer.cornerRadius = 8.0
innerContainer.layer.shadowColor = UIColor.blackColor().CGColor
innerContainer.layer.shadowOffset = CGSizeMake(2.5, 2.5)
innerContainer.layer.shadowRadius = 2.0
innerContainer.layer.shadowOpacity = 0.5
self.addSubview(innerContainer)
var headerLabel = UILabel()
headerLabel.frame = CGRectMake(10, 10, innerContainer.frame.size.width - 130, 30)
headerLabel.backgroundColor = UIColor.clearColor()
headerLabel.textColor = UIColor.whiteColor()
headerLabel.text = titleText
headerLabel.font = UIFont(name: "Helvetica", size: 15.0)
innerContainer.addSubview(headerLabel)
var bottomBar = UIView()
bottomBar.frame = CGRectMake(0, CGFloat(DROPDOWNVIEW_HEADER_HEIGHT - 2), innerContainer.frame.size.width, 2)
bottomBar.backgroundColor = UIColor.whiteColor()
innerContainer.addSubview(bottomBar)
DropTableView = UITableView(frame: CGRectMake(0, CGFloat(DROPDOWNVIEW_HEADER_HEIGHT), innerContainer.frame.size.width, innerContainer.frame.size.height - 50), style: UITableViewStyle.Plain)
DropTableView.separatorColor = UIColor(white: 1, alpha: 0.2)
DropTableView.separatorInset = UIEdgeInsetsZero
DropTableView.backgroundColor = UIColor.clearColor()
DropTableView.delegate = self
DropTableView.dataSource = self
innerContainer.addSubview(DropTableView)
if isMultipleSelection {
//var doneButton = UIButton(frame: CGRectMake(innerContainer.frame.size.width - 100, 10, 80, 30))
var doneButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
doneButton.frame = CGRectMake(innerContainer.frame.size.width - 100, 10, 80, 30)
doneButton.setImage(UIImage(named: "[email protected]"), forState: .Normal)
//doneButton.addTarget(self, action: "Click_Done", forControlEvents: UIControlEvents.TouchUpInside)
doneButton.addTarget(self, action: "Click_Done:", forControlEvents: .TouchUpInside)
innerContainer.addSubview(doneButton)
//doneButton(but
}
}
func calculateDropdownContainerSize(totalCout: NSInteger) -> CGRect {
var bounds: CGRect = UIScreen.mainScreen().bounds
var width:CGFloat = bounds.size.width - 30
var height:CGFloat = bounds.size.height - 100
var totalTableH = CGFloat((totalCout*40) + 50)
var frameBounds: CGRect
if height > totalTableH {
frameBounds = CGRectMake(15, (bounds.size.height - totalTableH)/2, width, totalTableH)
}else {
frameBounds = CGRectMake(15, (bounds.size.height - height)/2, width, height)
}
return frameBounds
}
//
// UITAbleview data sources
//
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DropDownOption.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIndentifier = "CellIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(reuseIndentifier) as? UITableViewCell
cell = JBDropDownCell(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIndentifier)
cell?.selectionStyle = UITableViewCellSelectionStyle.None
var tickImage = UIImageView()
if (arryData.containsObject(indexPath)) {
tickImage.frame = CGRectMake(tableView.frame.size.width - 50 , 6, 27, 27)
tickImage.image = UIImage(named: "[email protected]")
}else {
tickImage.removeFromSuperview()
println("Remove tick mark")
}
cell?.addSubview(tickImage)
//we know that cell is not empty now so we use ! to force unwrapping
cell!.contentView.backgroundColor = UIColor.clearColor()
cell!.textLabel.text = NSString(format: "%@", DropDownOption.objectAtIndex(indexPath.row) as NSString)
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("indexpath => \(indexPath.row)")
if isMultipleSelection {
if (arryData.containsObject(indexPath)) {
arryData.removeObject(indexPath)
}else{
arryData.addObject(indexPath)
}
tableView.reloadData()
}else {
jbDelegate?.DropDownListViewDidSelect(indexPath.row)
self.showFadeOut()
}
}
//
// Show Drope down with animation
//
func showDropdownWithAnimation(parentView: UIView, animation: Bool) {
parentView.addSubview(self)
if animation {
self.showFadeIn()
}
}
func showFadeIn() {
self.transform = CGAffineTransformMakeScale(1.3, 1.3);
self.alpha = 0;
UIView.animateWithDuration(0.35, animations: {
self.alpha = 1
self.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
}
func showFadeOut() {
UIView.animateWithDuration(0.35, animations: {
self.transform = CGAffineTransformMakeScale(1.3, 1.3)
self.alpha = 0.0
}, completion: { finished in
self.removeFromSuperview()
})
}
func callFingerTapToExit() {
var singleTap = UITapGestureRecognizer(target: self, action: Selector("dissmissDropDownList"))
singleTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(singleTap)
}
func dissmissDropDownList() {
self.showFadeOut()
self.removeFromSuperview()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var touch = touches.anyObject() as UITouch
if touch.view.isKindOfClass(UIView) {
self.showFadeOut()
}
}
func Click_Done(sender: UIButton!){
var dataList = NSMutableArray()
for (var i = 0; i < arryData.count; i++) {
var arrayIndexPath = arryData.objectAtIndex(i) as NSIndexPath
dataList.addObject(DropDownOption.objectAtIndex(arrayIndexPath.row))
}
jbDelegate?.DropDownListViewDataList(dataList)
self.showFadeOut()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 960ca0937e7f6da5039565695da4f84c | 34.728346 | 203 | 0.632287 | 4.884284 | false | false | false | false |
boluomeng/Charts | ChartsRealm/Classes/Data/RealmPieDataSet.swift | 1 | 2511 | //
// RealmPieDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import Realm.Dynamic
open class RealmPieDataSet: RealmBaseDataSet, IPieChartDataSet
{
open override func initialize()
{
self.valueTextColor = NSUIColor.white
self.valueFont = NSUIFont.systemFont(ofSize: 13.0)
}
// MARK: - Styling functions and accessors
private var _sliceSpace = CGFloat(0.0)
/// the space in pixels between the pie-slices
/// **default**: 0
/// **maximum**: 20
open var sliceSpace: CGFloat
{
get
{
return _sliceSpace
}
set
{
var space = newValue
if (space > 20.0)
{
space = 20.0
}
if (space < 0.0)
{
space = 0.0
}
_sliceSpace = space
}
}
/// indicates the selection distance of a pie slice
open var selectionShift = CGFloat(18.0)
open var xValuePosition: PieChartDataSet.ValuePosition = .insideSlice
open var yValuePosition: PieChartDataSet.ValuePosition = .insideSlice
/// When valuePosition is OutsideSlice, indicates line color
open var valueLineColor: NSUIColor? = NSUIColor.black
/// When valuePosition is OutsideSlice, indicates line width
open var valueLineWidth: CGFloat = 1.0
/// When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size
open var valueLinePart1OffsetPercentage: CGFloat = 0.75
/// When valuePosition is OutsideSlice, indicates length of first half of the line
open var valueLinePart1Length: CGFloat = 0.3
/// When valuePosition is OutsideSlice, indicates length of second half of the line
open var valueLinePart2Length: CGFloat = 0.4
/// When valuePosition is OutsideSlice, this allows variable line length
open var valueLineVariableLength: Bool = true
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = super.copyWithZone(zone) as! RealmPieDataSet
copy._sliceSpace = _sliceSpace
copy.selectionShift = selectionShift
return copy
}
}
| apache-2.0 | cf00ed4b9d7c6b0238a0c3594853665f | 26.593407 | 96 | 0.633612 | 4.667286 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftDemo/SwiftDemo/Common/Tools/Font/JWFontAdaptor.swift | 1 | 1094 | //
// JWFontAdaptor.swift
// SwiftDemo
//
// Created by apple on 2017/11/7.
// Copyright © 2017年 UgoMedia. All rights reserved.
//
import UIKit
let IPHONE5_INCREMENT : CGFloat = 0.0
let IPHONE6_INCREMENT : CGFloat = 0.0
let IPHONE6PLUS_INCREMENT : CGFloat = 0.0
class JWFontAdaptor: NSObject {
@objc class func adjustFont(fixFont font : UIFont) -> UIFont {
var newFont = UIFont()
if iPhone5 {
newFont = UIFont.init(name: font.fontName, size: (font.pointSize + IPHONE5_INCREMENT))!
}else if (JWSwiftConst.IPhone6()){
newFont = UIFont.init(name: font.fontName, size: (font.pointSize + IPHONE6_INCREMENT))!
}else if (JWSwiftConst.IPhone6p()){
newFont = UIFont.init(name: font.fontName, size: (font.pointSize + IPHONE6PLUS_INCREMENT))!
}else{
newFont = font;
}
return newFont;
}
@objc class func adjustFont(fixFontSize fontSize : CGFloat) -> UIFont {
return JWFontAdaptor.adjustFont(fixFont: UIFont.systemFont(ofSize: fontSize));
}
}
| apache-2.0 | d066a747ef41a7c13c646957d8ada939 | 27.710526 | 103 | 0.629698 | 3.736301 | false | false | false | false |
izandotnet/ULAQ | ULAQ/Snake.swift | 1 | 3825 | //
// Snake.swift
// ULAQ
//
// Created by Rohaizan Roosley on 07/05/2017.
// Copyright © 2017 Rohaizan Roosley. All rights reserved.
//
import SpriteKit
class Snake: SKSpriteNode{
//0.05 expert
//0.15 normal
//0.25 beginner
var snakeSpeed:Double = 0.25
var snakeHead = SKSpriteNode()
var snakebody = SKSpriteNode()
var snakeBodies = [SKSpriteNode]()
var parentScene: SKScene?
var headSkin:String = "Snakehead"
var bodySkin:String = "Body1"
func getSkinSettings(){
let defaults = UserDefaults.standard
var value = defaults.integer(forKey: skinConstant)
if value == 0 {
value = 1
defaults.set(value, forKey: skinConstant)
}
switch value {
case 1:
headSkin = "Snakehead"
bodySkin = "Body1"
case 2:
headSkin = "Snakehead2"
bodySkin = "Body2"
case 3:
headSkin = "Snakehead3"
bodySkin = "Body3"
case 4:
headSkin = "Snakehead4"
bodySkin = "Body4"
case 5:
headSkin = "Snakehead5"
bodySkin = "Body5"
default:
return
}
}
func getSpeedSetting(){
let defaults = UserDefaults.standard
let value = defaults.integer(forKey: firstTimerConstant)
if value == 0 {
defaults.set(1, forKey: firstTimerConstant)
}
self.snakeSpeed = defaults.double(forKey: difficultyConstant)
}
func new(){
self.getSkinSettings()
snakeHead = SKSpriteNode(imageNamed: headSkin)
snakeHead.position = CGPoint(x: 0,y: 0)
snakeHead.physicsBody = SKPhysicsBody(circleOfRadius: snakeHead.size.width / 2.0)
snakeHead.physicsBody?.affectedByGravity = false
snakeHead.physicsBody?.usesPreciseCollisionDetection = true
snakeHead.physicsBody?.isDynamic = true
snakeHead.physicsBody?.restitution = 0
snakeHead.physicsBody?.friction = 0
snakeHead.physicsBody?.categoryBitMask = headUnit
snakeHead.physicsBody?.contactTestBitMask = appleUnit | borderUnit | bodyUnit | obstacleUnit
snakeHead.physicsBody?.collisionBitMask = appleUnit | borderUnit | bodyUnit | obstacleUnit
snakeHead.run(SKAction.playSoundFileNamed("startgame.mp3",waitForCompletion:false));
snakeBodies.append(snakeHead)
parentScene?.addChild(snakeHead)
for _ in 0 ..< 3 {
self.createBody()
}
self.getSpeedSetting()
}
private func createBody(){
snakebody = SKSpriteNode(imageNamed: bodySkin)
snakebody.position = CGPoint(x: snakeBodies[snakeBodies.count-1].position.x,y: snakeBodies[snakeBodies.count-1].position.y)
snakebody.physicsBody = SKPhysicsBody(circleOfRadius: snakebody.size.width / 2.0)
snakebody.physicsBody?.affectedByGravity = false
snakebody.physicsBody?.isDynamic = true
snakebody.physicsBody?.restitution = 1
snakebody.physicsBody?.friction = 0
if(snakeBodies.count > 3){
snakebody.physicsBody?.usesPreciseCollisionDetection = true
snakebody.physicsBody?.categoryBitMask = bodyUnit
snakebody.physicsBody?.collisionBitMask = headUnit
snakebody.physicsBody?.contactTestBitMask = headUnit
}
snakeBodies.append(snakebody)
parentScene?.addChild(snakebody)
}
func eat(apple: Apple){
apple.remove()
self.createBody()
snakebody.run(SKAction.playSoundFileNamed("eat.mp3",waitForCompletion:false));
}
}
| mit | 7da310f211322edcd4446c14fc9d7270 | 29.110236 | 131 | 0.601203 | 4.618357 | false | false | false | false |
milseman/swift | test/attr/attr_escaping.swift | 9 | 9638 | // RUN: %target-typecheck-verify-swift -swift-version 4
@escaping var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}}
func paramDeclEscaping(@escaping fn: (Int) -> Void) {} // expected-error {{attribute can only be applied to types, not declarations}}
func wrongParamType(a: @escaping Int) {} // expected-error {{@escaping attribute only applies to function types}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}}
// expected-error@-1{{@noescape is the default and has been removed}} {{29-39=}}
func takesEscaping(_ fn: @escaping () -> Int) {} // ok
func callEscapingWithNoEscape(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
// expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
let _ = fn // expected-error{{non-escaping parameter 'fn' may only be called}}
}
typealias IntSugar = Int
func callSugared(_ fn: () -> IntSugar) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
struct StoresClosure {
var closure : () -> Int
init(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{14-14=@escaping }}
closure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
func arrayPack(_ fn: () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }}
return [fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}}
}
func arrayPack(_ fn: @escaping () -> Int, _ fn2 : () -> Int) -> [() -> Int] {
// expected-note@-1{{parameter 'fn2' is implicitly non-escaping}} {{53-53=@escaping }}
return [fn, fn2] // expected-error{{using non-escaping parameter 'fn2' in a context expecting an @escaping closure}}
}
}
func takesEscapingBlock(_ fn: @escaping @convention(block) () -> Void) {
fn()
}
func callEscapingWithNoEscapeBlock(_ fn: () -> Void) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{42-42=@escaping }}
takesEscapingBlock(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingAutoclosure(_ fn: @autoclosure @escaping () -> Int) {}
func callEscapingAutoclosureWithNoEscape(_ fn: () -> Int) {
takesEscapingAutoclosure(1+1)
}
func callEscapingAutoclosureWithNoEscape_2(_ fn: () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}}
takesEscapingAutoclosure(fn()) // expected-error{{closure use of non-escaping parameter 'fn' may allow it to escape}}
}
func callEscapingAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}}
takesEscapingAutoclosure(fn()) // expected-error{{closure use of non-escaping parameter 'fn' may allow it to escape}}
}
let foo: @escaping (Int) -> Int // expected-error{{@escaping attribute may only be used in function parameter position}} {{10-20=}}
struct GenericStruct<T> {}
func misuseEscaping(_ a: @escaping Int) {} // expected-error{{@escaping attribute only applies to function types}} {{26-38=}}
func misuseEscaping(_ a: (@escaping Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{27-39=}}
func misuseEscaping(opt a: @escaping ((Int) -> Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{28-38=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: (@escaping (Int) -> Int)?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(nest a: (((@escaping (Int) -> Int))?)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(iuo a: (@escaping (Int) -> Int)!) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{29-39=}}
// expected-note@-1{{closure is already escaping in optional type argument}}
func misuseEscaping(_ a: Optional<@escaping (Int) -> Int>, _ b: Int) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{35-45=}}
func misuseEscaping(_ a: (@escaping (Int) -> Int, Int)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [@escaping (Int) -> Int]?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}}
func misuseEscaping(_ a: [Int : @escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{33-43=}}
func misuseEscaping(_ a: GenericStruct<@escaping (Int) -> Int>) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{40-50=}}
func takesEscapingGeneric<T>(_ fn: @escaping () -> T) {}
func callEscapingGeneric<T>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{35-35=@escaping }}
takesEscapingGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class Super {}
class Sub: Super {}
func takesEscapingSuper(_ fn: @escaping () -> Super) {}
func callEscapingSuper(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{30-30=@escaping }}
takesEscapingSuper(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func takesEscapingSuperGeneric<T: Super>(_ fn: @escaping () -> T) {}
func callEscapingSuperGeneric(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func callEscapingSuperGeneric<T: Sub>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{45-45=@escaping }}
takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
func testModuloOptionalness() {
var iuoClosure: (() -> Void)! = nil
func setIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{28-28=@escaping }}
iuoClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var iuoClosureExplicit: ImplicitlyUnwrappedOptional<() -> Void>
func setExplicitIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{36-36=@escaping }}
iuoClosureExplicit = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
var deepOptionalClosure: (() -> Void)???
func setDeepOptionalClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }}
deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
}
}
// Check that functions in vararg position are @escaping
func takesEscapingFunction(fn: @escaping () -> ()) {}
func takesArrayOfFunctions(array: [() -> ()]) {}
func takesVarargsOfFunctions(fns: () -> ()...) {
takesArrayOfFunctions(array: fns)
for fn in fns {
takesEscapingFunction(fn: fn)
}
}
func takesVarargsOfFunctionsExplicitEscaping(fns: @escaping () -> ()...) {} // expected-error{{@escaping attribute may only be used in function parameter position}}
func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}}
takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
}
class FooClass {
var stored : Optional<(()->Int)->Void> = nil
var computed : (()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // ok
}
var computedEscaping : (@escaping ()->Int)->Void {
get { return stored! }
set(newValue) { stored = newValue } // expected-error{{cannot assign value of type '(@escaping () -> Int) -> Void' to type 'Optional<(() -> Int) -> Void>'}}
}
}
// A call of a closure literal should be non-escaping
func takesInOut(y: inout Int) {
_ = {
y += 1 // no-error
}()
_ = ({
y += 1 // no-error
})()
_ = { () in
y += 1 // no-error
}()
_ = ({ () in
y += 1 // no-error
})()
_ = { () -> () in
y += 1 // no-error
}()
_ = ({ () -> () in
y += 1 // no-error
})()
}
class HasIVarCaptures {
var x: Int = 0
func method() {
_ = {
x += 1 // no-error
}()
_ = ({
x += 1 // no-error
})()
_ = { () in
x += 1 // no-error
}()
_ = ({ () in
x += 1 // no-error
})()
_ = { () -> () in
x += 1 // no-error
}()
_ = ({ () -> () in
x += 1 // no-error
})()
}
}
| apache-2.0 | 7e7883f39530960636b36f55c30f179c | 43.009132 | 171 | 0.661029 | 3.82157 | false | false | false | false |
1738004401/Swift3.0-- | SwiftCW/SwiftCW/Util/Manager/DAOManager.swift | 1 | 5527 | //
// DAOManager.swift
// SwiftCW
//
// Created by YiXue on 17/3/19.
// Copyright © 2017年 赵刘磊. All rights reserved.
//
import UIKit
import FMDB
class DAOManager: NSObject {
private static let manager:DAOManager = DAOManager()
var dbQueue: FMDatabaseQueue?
class func shareManager() -> DAOManager!{
return manager
}
func openDB(DBName: String)
{
// 1.根据传入的数据库名称拼接数据库路径
let path = DBName.docDir()
print(path)
// 2.创建数据库对象
// 注意: 如果是使用FMDatabaseQueue创建数据库对象, 那么就不用打开数据库
dbQueue = FMDatabaseQueue(path: path)
// 4.创建表
creatTable()
}
private func creatTable()
{
// 1.编写SQL语句
let sql = "CREATE TABLE IF NOT EXISTS T_Status( \n" +
"statusId INTEGER PRIMARY KEY, \n" +
"statusText TEXT, \n" +
"userId INTEGER, \n" +
"createDate TEXT NOT NULL DEFAULT (datetime('now', 'localtime')) \n" +
"); \n"
// 2.执行SQL语句
dbQueue!.inDatabase { (db) -> Void in
db?.executeUpdate(sql, withArgumentsIn: nil)
}
}
/// 清空过期的数据
class func cleanStatuses() {
// let date = NSDate()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en") as Locale!
let date = NSDate(timeIntervalSinceNow: -60)
let dateStr = formatter.string(from: date as Date)
// print(dateStr)
// 1.定义SQL语句
let sql = "DELETE FROM T_Status WHERE createDate <= '\(dateStr)';"
// 2.执行SQL语句
DAOManager.shareManager().dbQueue?.inDatabase({ (db) -> Void in
db?.executeUpdate(sql, withArgumentsIn: nil)
})
}
// /// 加载微博数据
// class func loadStatuses(since_id: Int, max_id: Int, finished: @escaping ([[String: AnyObject]]?, _ error: NSError?)->()) {
//
// // 1.从本地数据库中获取
// loadCacheStatuses(since_id: since_id, max_id: max_id) { (array) -> () in
//
// // 2.如果本地有, 直接返回
// if !array!.isEmpty
// {
// print("从数据库中获取")
// finished(array, nil)
// return
// }
//
//
//
//
// }
//
// }
//
/// 从数据库中加载缓存数据
class func loadCacheStatuses(since_id: Int, max_id: Int, finished: @escaping ([[String: AnyObject]]?)->()) {
// 1.定义SQL语句
var sql = "SELECT * FROM T_Status \n"
if since_id > 0
{
sql += "WHERE statusId > \(since_id) \n"
}else if max_id > 0
{
sql += "WHERE statusId < \(max_id) \n"
}
sql += "ORDER BY statusId DESC \n"
sql += "LIMIT 20; \n"
// 2.执行SQL语句
DAOManager.shareManager().dbQueue?.inDatabase({ (db) -> Void in
// 2.1查询数据
// 返回字典数组的原因:通过网络获取返回的也是字典数组,
// 让本地和网络返回的数据类型保持一致, 以便于我们后期处理
var statuses = [[String: AnyObject]]()
if let res = db?.executeQuery(sql, withArgumentsIn: nil)
{
// 2.2遍历取出查询到的数据
while res.next()
{
// 1.取出数据库存储的一条微博字符串
let dictStr = res.string(forColumn: "statusText") as String
// 2.将微博字符串转换为微博字典
let data = dictStr.data(using: String.Encoding.utf8)!
let dict = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
statuses.append(dict)
}
}
// 3.返回数据
finished(statuses)
})
}
/// 缓存微博数据
class func cacheStatuses(statuses: [[String: AnyObject]])
{
// 0. 准备数据
let userId:String! = SWUser.curUser()?.uid!
// 1.定义SQL语句
let sql = "INSERT OR REPLACE INTO T_Status" +
"(statusId, statusText, userId)" +
"VALUES" +
"(?, ?, ?);"
// 2.执行SQL语句
DAOManager.shareManager().dbQueue?.inTransaction({ (db, rollback) -> Void in
for dict in statuses
{
let statusId = dict["id"]!
// JSON -> 二进制 -> 字符串
let data = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted)
let statusText = String(data: data, encoding: String.Encoding.utf8)!
if !(db?.executeUpdate(sql, withArgumentsIn: [statusId, statusText, userId]))!
{
// rollback?.advanced(by: 1)
}
}
})
}
}
| mit | 00e127ee2e7ddb4c9d3feb2577791d2d | 27.908046 | 161 | 0.478926 | 4.280851 | false | false | false | false |
dvl/imagefy-ios | imagefy/Classes/AlertViewController/AlmostThereView.swift | 1 | 3048 | //
// AlmostThereView.swift
// imagefy
//
// Created by Alan on 5/22/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import UIKit
class AlmostThereView: UIView {
let kMaxValue: Float = 1000.0
@IBOutlet weak var productImage: UIImageView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var contentViewImage: UIView!
@IBOutlet weak var priceSlide: UISlider!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var briefText: UITextField!
var price: Float = 0.0
weak var delegate: AlmostThereViewDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
class func loadFromNib() -> AlmostThereView {
let view = NSBundle.mainBundle().loadNibNamed("AlmostThereView", owner: self, options: nil).first as! AlmostThereView
let internalBorder = CALayer()
internalBorder.frame = CGRectMake(view.productImage.frame.origin.x-2, view.productImage.frame.origin.y-2, view.productImage.frame.size.width+4, view.productImage.frame.size.height+4)
internalBorder.borderColor = kAccentColor.CGColor
internalBorder.borderWidth = 2.0
internalBorder.cornerRadius = (view.productImage.frame.size.height+4)/2
view.contentViewImage.layer.addSublayer(internalBorder)
return view
}
class func loadFromNib(productImage: UIImage) -> AlmostThereView {
let view = NSBundle.mainBundle().loadNibNamed("AlmostThereView", owner: self, options: nil).first as! AlmostThereView
view.productImage.image = productImage
view.closeButton.setImage(UIImage(named: "ic_close_x")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
view.closeButton.tintColor = kSecondaryTextColor
let internalBorder = CALayer()
internalBorder.frame = CGRectMake(view.productImage.frame.origin.x-2, view.productImage.frame.origin.y-2, view.productImage.frame.size.width+4, view.productImage.frame.size.height+4)
internalBorder.borderColor = kAccentColor.CGColor
internalBorder.borderWidth = 2.0
internalBorder.cornerRadius = (view.productImage.frame.size.height+4)/2
view.contentViewImage.layer.addSublayer(internalBorder)
return view
}
@IBAction func slidePrice(sender: UISlider) {
self.price = priceSlide.value * self.kMaxValue
self.priceLabel.text = "U$ \(Int(self.price)),00"
}
@IBAction func slidePriceChanged(sender: AnyObject) {
}
@IBAction func closeAlert(sender: AnyObject) {
self.removeFromSuperview()
}
@IBAction func okAction(sender: UIButton) {
self.removeFromSuperview()
if let d = self.delegate {
let model = AlmostThereModelView(productImage: self.productImage.image, brief: self.briefText.text ?? "", priceValue: self.price)
d.setupSuccess(model)
}
}
}
| mit | b92c842bc9ed1f00b930fa1994e46aaf | 35.27381 | 190 | 0.671152 | 4.371593 | false | false | false | false |
tjw/swift | test/SILGen/partial_apply_generic.swift | 1 | 4714 |
// RUN: %target-swift-frontend -module-name partial_apply_generic -emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol Panda {
associatedtype Cuddles : Foo
}
protocol Foo {
static func staticFunc()
func instanceFunc()
func makesSelfNonCanonical<T : Panda>(_: T) where T.Cuddles == Self
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic14getStaticFunc1{{[_0-9a-zA-Z]*}}F
func getStaticFunc1<T: Foo>(t: T.Type) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: apply [[REF]]<T>(%0)
return t.staticFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.staticFunc!1
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @$S21partial_apply_generic14getStaticFunc2{{[_0-9a-zA-Z]*}}F
func getStaticFunc2<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: apply [[REF]]<T>
return T.staticFunc
// CHECK-NOT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc1{{[_0-9a-zA-Z]*}}F
func getInstanceFunc1<T: Foo>(t: T) -> () -> () {
// CHECK-NOT: alloc_stack $T
// CHECK-NOT: copy_addr %0 to [initialization]
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: apply [[REF]]<T>
return t.instanceFunc
// CHECK-NOT: dealloc_stack
// CHECK-NOT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : @trivial $*Self):
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.instanceFunc!1
// CHECK-NEXT: [[STACK:%.*]] = alloc_stack $Self
// CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[STACK]]
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<Self>([[STACK]])
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc2{{[_0-9a-zA-Z]*}}F
func getInstanceFunc2<T: Foo>(t: T) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<T>(
return T.instanceFunc
// CHECK-NOT: destroy_addr %0 : $*
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic16getInstanceFunc3{{[_0-9a-zA-Z]*}}F
func getInstanceFunc3<T: Foo>(t: T.Type) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [callee_guaranteed] [[REF]]<T>(
return t.instanceFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @$S21partial_apply_generic23getNonCanonicalSelfFunc1tyq_cxcxm_t7CuddlesQy_RszAA5PandaR_r0_lF : $@convention(thin) <T, U where T == U.Cuddles, U : Panda> (@thick T.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @owned @callee_guaranteed (@in_guaranteed U) -> () {
func getNonCanonicalSelfFunc<T : Foo, U : Panda>(t: T.Type) -> (T) -> (U) -> () where U.Cuddles == T {
// CHECK: [[REF:%.*]] = function_ref @$S21partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in_guaranteed τ_1_0) -> ()
// CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<T, U>()
return t.makesSelfNonCanonical
// CHECK-NEXT: return [[CLOSURE]]
}
// curry thunk of Foo.makesSelfNonCanonical<A where ...> (A1) -> ()
// CHECK-LABEL: sil shared [thunk] @$S21partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <Self><T where Self == T.Cuddles, T : Panda> (@in_guaranteed Self) -> @owned @callee_guaranteed (@in_guaranteed T) -> () {
// CHECK: bb0([[ARG:%.*]] : @trivial $*Self):
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.makesSelfNonCanonical!1 : <Self><T where Self == T.Cuddles, T : Panda> (Self) -> (T) -> () : $@convention(witness_method: Foo) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK-NEXT: [[STACK:%.*]] = alloc_stack $Self
// CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[STACK]] : $*Self
// CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<Self, T>([[STACK]])
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: return [[CLOSURE]]
| apache-2.0 | 69b0ca9f53927bea375351e07a75496e | 50.648352 | 299 | 0.657447 | 2.930175 | false | false | false | false |
PokemonGoSucks/pgoapi-swift | PGoApi/Classes/Unknown6/subFuncI.swift | 1 | 34244 | //
// subFuncA.swift
// Pods
//
// Created by PokemonGoSucks on 2016-08-10
//
//
import Foundation
internal class subFuncI {
internal func subFuncI(_ input:inout Array<UInt32>) {
var v = Array<UInt32>(repeating: 0, count: 469)
v[0] = input[18]
v[1] = (input[10] & ~v[0])
let part0 = ((input[97] ^ (input[10] & ~input[195])))
let part1 = (((input[2] & ~part0) ^ input[18]))
let part2 = (((input[79] ^ v[0]) | input[56]))
let part3 = ((input[81] ^ part2))
v[2] = (((((input[173] ^ input[86]) ^ input[10]) ^ input[45]) ^ (part3 & ~input[125])) ^ (part1 & ~input[56]))
v[3] = ~input[56]
v[4] = (v[2] & ~input[182])
let part4 = ((input[97] ^ (input[10] & ~input[195])))
let part5 = (((input[2] & ~part4) ^ input[18]))
let part6 = (((input[79] ^ v[0]) | input[56]))
let part7 = ((input[81] ^ part6))
v[5] = (((((input[173] ^ input[86]) ^ input[10]) ^ input[45]) ^ (part7 & ~input[125])) ^ (part5 & v[3]))
v[6] = input[157]
v[7] = input[193]
v[8] = input[2]
let part8 = (((v[2] & ~input[7]) ^ input[180]))
v[9] = ((((v[2] & ~input[4]) ^ input[99]) ^ (input[37] & ~part8)) ^ input[22])
let part9 = ((v[4] ^ input[174]))
v[10] = (((input[175] ^ input[70]) ^ (input[93] & v[5])) ^ (input[37] & ~part9))
input[175] = v[10]
v[11] = v[9]
v[12] = input[134]
v[13] = v[11]
input[22] = v[11]
v[14] = v[12]
v[15] = ~v[8]
v[16] = (v[12] & input[10])
v[17] = (input[2] | v[6])
let part10 = (((v[5] & input[113]) ^ input[172]))
v[18] = (((input[2] ^ input[142]) ^ (v[5] & ~input[19])) ^ (input[37] & ~part10))
let part11 = ((input[181] ^ input[10]))
let part12 = (((part11 & ~v[8]) ^ input[194]))
let part13 = ((v[16] ^ input[64]))
let part14 = (((((v[16] ^ input[18]) ^ (part13 & ~v[8])) ^ (part12 & v[3])) | input[125]))
let part15 = ((((~v[8] & v[6]) ^ v[7]) | input[56]))
v[19] = ((((input[25] ^ v[12]) ^ v[17]) ^ part15) ^ part14)
v[20] = (v[18] & input[24])
v[21] = (v[18] | input[24])
v[22] = ((v[18] & input[24]) & input[199])
v[23] = (v[18] ^ input[24])
v[24] = input[17]
v[25] = (input[36] ^ input[167])
v[26] = input[26]
let part16 = ((v[18] | input[24]))
v[27] = (part16 & input[199])
v[28] = (~v[18] & input[199])
v[29] = (v[19] & ~v[24])
v[30] = input[9]
v[31] = input[91]
let part17 = (((v[5] & input[160]) ^ input[166]))
v[32] = ((((v[5] & input[186]) ^ input[120]) ^ input[16]) ^ (input[37] & ~part17))
v[33] = (v[19] & v[31])
input[16] = v[32]
v[34] = v[19]
v[35] = (v[18] ^ input[131])
input[113] = v[18]
let part18 = ((v[26] | v[19]))
v[36] = (v[25] ^ part18)
input[36] = v[36]
v[37] = v[35]
input[131] = v[35]
v[38] = (v[22] ^ v[20])
input[202] = (v[22] ^ v[20])
v[39] = input[10]
v[40] = input[64]
v[41] = (v[28] ^ v[23])
input[138] = (v[28] ^ v[23])
v[42] = (v[40] & v[39])
v[43] = input[112]
input[116] = v[27]
v[44] = (v[34] & v[43])
v[45] = (v[33] ^ v[24])
v[46] = (v[34] & input[44])
v[47] = input[10]
v[48] = (v[29] ^ v[31])
v[49] = (v[27] ^ v[20])
input[161] = (v[27] ^ v[20])
v[50] = input[1]
v[51] = ((v[33] ^ v[30]) | v[50])
v[52] = (v[42] ^ v[17])
v[53] = (v[47] & ~v[14])
v[54] = ((v[34] & v[24]) ^ v[31])
v[55] = (v[34] & ~v[31])
v[56] = (v[46] ^ input[68])
v[57] = (v[53] ^ input[64])
let part19 = ((v[45] | v[50]))
v[58] = (part19 ^ v[45])
v[59] = (v[54] & ~v[50])
v[60] = ((input[129] ^ v[44]) ^ v[51])
v[61] = (input[112] ^ v[44])
v[62] = input[1]
let part20 = (((v[34] & v[24]) ^ input[72]))
v[63] = (v[62] & ~part20)
v[64] = (input[129] ^ v[62])
let part21 = ((v[29] ^ v[31]))
v[65] = ((part21 & ~v[50]) ^ v[56])
let part22 = (((v[34] & ~v[30]) ^ v[24]))
v[66] = (~v[50] & part22)
v[67] = ((input[44] ^ input[52]) ^ (v[34] & input[68]))
v[68] = (v[58] | input[33])
v[69] = ((v[55] ^ v[30]) ^ v[59])
v[70] = input[33]
v[71] = ((v[51] ^ v[30]) | input[33])
let part23 = ((input[1] | (v[29] ^ v[30])))
v[72] = (((v[34] & ~input[112]) ^ v[30]) ^ part23)
let part24 = ((v[66] ^ v[61]))
v[73] = (part24 & ~v[70])
v[74] = (v[69] ^ v[68])
v[75] = ((input[1] & v[29]) ^ v[54])
let part25 = ((v[52] | input[56]))
let part26 = (((part25 ^ input[104]) | input[125]))
let part27 = (((v[57] & v[15]) | input[56]))
v[76] = (part27 ^ part26)
let part28 = ((input[1] | (v[29] ^ v[31])))
let part29 = ((part28 ^ v[30]))
v[77] = ((v[75] ^ input[12]) ^ (part29 & ~v[70]))
v[78] = ((input[0] ^ input[153]) ^ (input[88] & ~v[34]))
v[79] = input[63]
v[80] = ~v[79]
let part30 = ((v[1] ^ input[18]))
v[81] = (part30 & v[15])
let part31 = ((v[65] | input[33]))
let part32 = ((((part31 ^ v[63]) ^ v[56]) | v[79]))
v[82] = ((v[74] ^ input[195]) ^ part32)
let part33 = ((v[67] | input[33]))
let part34 = (((v[67] ^ part33) | v[79]))
v[83] = ((((v[64] ^ input[40]) ^ (v[34] & ~input[68])) ^ v[73]) ^ part34)
let part35 = ((v[55] | input[1]))
let part36 = ((((v[60] & ~v[70]) ^ part35) ^ v[48]))
input[98] ^= (v[74] ^ (v[79] & ~part36))
let part37 = ((v[72] ^ v[71]))
v[84] = (v[77] ^ (part37 & ~v[79]))
v[85] = (input[14] ^ input[148])
v[86] = input[42]
v[87] = v[83]
v[88] = input[108]
input[40] = v[83]
v[89] = (v[76] ^ v[86])
v[90] = (v[34] | v[88])
v[91] = input[47]
v[92] = v[84]
v[93] = (input[18] ^ input[66])
input[12] = v[84]
v[94] = (v[81] ^ v[91])
v[95] = input[62]
v[96] = input[5]
v[97] = v[82]
input[195] = v[82]
let part38 = ((v[34] | v[96]))
v[98] = (v[93] ^ part38)
input[5] = v[98]
input[14] = (v[85] ^ v[90])
v[99] = (~v[78] & v[95])
input[0] = v[78]
input[88] = v[99]
v[100] = (~v[78] & v[95])
input[167] = v[99]
v[101] = (v[78] & v[95])
input[81] = (v[78] & v[95])
let part39 = ((v[89] ^ v[94]))
v[102] = ~part39
v[103] = (v[85] ^ v[90])
v[104] = ((v[13] ^ v[85]) ^ v[90])
v[105] = (v[89] ^ v[94])
v[106] = ~input[58]
v[107] = input[1]
let part40 = (((v[89] ^ v[94]) | input[29]))
let part41 = ((part40 ^ input[107]))
let part42 = (((((v[102] & input[185]) ^ input[107]) ^ (input[1] & ~part41)) | input[63]))
let part43 = (((input[140] & v[102]) ^ input[184]))
v[108] = (((((v[107] & ~part43) ^ input[123]) ^ input[10]) ^ (v[102] & input[149])) ^ part42)
v[109] = (v[108] | v[18])
v[110] = input[58]
let part44 = (((v[102] & input[152]) ^ input[73]))
let part45 = (((v[107] & ~part44) ^ input[151]))
let part46 = (((v[102] & input[151]) ^ input[145]))
let part47 = (((v[89] ^ v[94]) | input[132]))
v[111] = ((((input[60] ^ input[170]) ^ part47) ^ (input[1] & ~part46)) ^ (part45 & v[80]))
v[112] = (v[108] & ~v[18])
v[113] = (v[18] & ~v[108])
let part48 = ((v[18] | input[58]))
v[114] = (part48 ^ v[18])
let part49 = (((v[89] ^ v[94]) | input[29]))
let part50 = ((part49 ^ input[107]))
let part51 = (((((v[102] & input[185]) ^ input[107]) ^ (input[1] & ~part50)) | input[63]))
let part52 = (((input[140] & v[102]) ^ input[184]))
v[115] = (((((v[107] & ~part52) ^ input[123]) ^ input[10]) ^ (v[102] & input[149])) ^ part51)
v[116] = (v[108] ^ v[18])
v[117] = ((v[108] | v[18]) | v[110])
v[118] = ((v[18] & ~v[108]) | v[110])
v[119] = (v[117] ^ v[108])
v[120] = ((v[108] & ~v[18]) ^ v[110])
v[121] = ((v[108] & ~v[18]) | v[110])
v[122] = input[31]
let part53 = ((v[110] | v[108]))
let part54 = ((part53 ^ v[108]))
v[123] = (((v[108] & ~v[18]) & v[106]) ^ (part54 & v[82]))
let part55 = ((v[89] ^ v[94]))
v[124] = (part55 & v[122])
v[125] = ((v[89] ^ v[94]) | v[122])
v[126] = (v[111] | v[13])
v[127] = ~input[80]
v[128] = (v[125] & ~v[122])
v[129] = ((v[121] ^ v[108]) ^ v[18])
v[130] = input[38]
let part56 = ((v[89] ^ v[94]))
v[131] = ((~v[122] & v[127]) & part56)
let part57 = ((v[111] | ~v[103]))
v[132] = (part57 & v[130])
v[133] = ((v[111] | v[104]) | v[130])
v[134] = ~v[130]
let part58 = ((v[111] | v[104]))
v[135] = ((part58 ^ v[103]) | input[38])
let part59 = ((v[111] | v[13]))
v[136] = (part59 & ~v[130])
v[137] = (v[98] & ~v[123])
v[138] = ((v[116] ^ input[58]) ^ (v[97] & ~v[119]))
v[139] = (input[31] & ~v[124])
input[60] = v[111]
let part60 = ((v[111] | v[104]))
input[157] = (v[133] ^ part60)
v[140] = input[118]
input[151] = (v[132] ^ v[103])
v[141] = v[140]
let part61 = ((((v[18] & v[106]) & v[97]) ^ v[18]))
v[142] = ((v[129] ^ (v[120] & v[97])) ^ (v[98] & ~part61))
v[143] = input[89]
let part62 = (((v[97] & v[106]) ^ v[114]))
v[144] = (((v[98] & ~part62) ^ (v[97] & v[118])) ^ v[112])
v[145] = (v[138] ^ v[137])
v[146] = (v[102] & input[31])
v[147] = v[145]
v[148] = (v[139] | input[80])
input[29] = v[115]
v[149] = input[141]
v[150] = (v[105] | input[152])
v[151] = input[105]
input[19] = v[142]
v[152] = (v[102] & v[151])
let part63 = ((v[105] | input[102]))
v[153] = (v[149] ^ part63)
input[118] = (v[136] ^ v[103])
input[89] = v[147]
v[154] = input[1]
input[91] = v[144]
v[155] = v[152]
v[156] = input[111]
v[157] = (v[154] & ~v[153])
input[123] = v[146]
v[158] = (v[128] ^ v[131])
v[159] = input[178]
input[111] = (v[128] ^ v[131])
let part64 = ((v[131] ^ v[125]))
v[160] = (v[159] & ~part64)
v[161] = ~input[23]
v[162] = ((v[102] & v[156]) ^ input[124])
let part65 = ((v[105] | input[75]))
v[163] = (part65 ^ v[143])
v[164] = input[7]
let part66 = ((v[111] | v[13]))
input[73] = (v[135] ^ part66)
let part67 = (((v[160] ^ ((v[161] & v[127]) & v[105])) ^ v[125]))
v[165] = (part67 & v[164])
v[166] = input[178]
v[167] = (v[148] ^ v[146])
input[134] = (v[148] ^ v[124])
input[104] = v[128]
v[168] = (((input[28] ^ (v[166] & ~v[158])) ^ v[148]) ^ v[124])
v[169] = (v[105] | input[146])
v[170] = (v[125] & v[127])
v[171] = (v[125] | input[80])
v[172] = (v[139] ^ v[170])
v[173] = v[170]
v[174] = input[80]
input[72] = v[172]
v[175] = (v[105] | v[174])
v[176] = (v[146] & v[127])
v[177] = ((v[124] & v[127]) ^ v[124])
let part68 = (((v[124] & v[127]) ^ v[146]))
v[178] = (((v[146] & v[127]) ^ v[128]) ^ (part68 & v[161]))
let part69 = ((v[105] | input[23]))
let part70 = (((part69 ^ v[105]) ^ v[176]))
v[179] = (input[178] & ~part70)
input[44] = v[178]
let part71 = ((v[171] ^ v[124]))
v[180] = (v[172] ^ (part71 & v[161]))
let part72 = ((((v[177] & v[161]) ^ v[158]) ^ v[179]))
v[181] = (input[7] & ~part72)
let part73 = ((v[172] | input[23]))
v[182] = ((v[168] ^ part73) ^ v[165])
v[183] = (v[177] ^ input[71])
v[184] = (input[1] & ~v[163])
v[185] = (input[50] ^ v[150])
v[186] = v[182]
input[28] = v[182]
v[187] = (v[16] & v[15])
let part74 = (((v[124] ^ v[175]) | input[23]))
let part75 = ((part74 ^ v[128]))
v[188] = (part75 & input[178])
v[189] = ((v[162] ^ (v[185] & input[1])) | input[63])
v[190] = ~v[111]
v[191] = (~v[111] & v[104])
v[192] = ((((input[8] ^ input[115]) ^ v[155]) ^ v[157]) ^ v[189])
v[193] = (v[191] ^ v[13])
let part76 = ((v[191] ^ v[103]))
v[194] = (part76 & v[134])
v[195] = (((v[180] ^ input[54]) ^ v[188]) ^ v[181])
let part77 = ((input[94] ^ v[167]))
v[196] = (input[178] & ~part77)
let part78 = ((input[80] | v[124]))
let part79 = ((part78 ^ v[124]))
v[197] = ((v[183] & input[178]) ^ (input[23] & ~part79))
input[172] = ((input[38] & ~v[193]) ^ v[103])
v[198] = (v[13] & ~v[103])
v[199] = (input[7] & ~v[197])
let part80 = ((v[111] | v[13]))
input[184] = (((v[13] & ~v[111]) ^ v[103]) ^ (input[38] & ~part80))
input[8] = v[192]
let part81 = ((v[111] | v[13]))
v[200] = (part81 ^ v[13])
v[201] = (v[171] ^ input[31])
v[202] = ((v[178] ^ input[32]) ^ v[196])
v[203] = (input[38] & ~v[200])
input[181] = (v[194] ^ v[200])
let part82 = ((v[111] | v[104]))
input[140] = (v[203] ^ part82)
let part83 = ((v[111] | v[104]))
v[204] = (part83 ^ v[104])
v[205] = (v[202] ^ v[199])
v[206] = input[38]
input[189] = ((v[206] ^ v[13]) ^ v[111])
let part84 = (((v[103] & ~v[13]) ^ v[111]))
input[108] = ((v[13] & ~v[198]) ^ (v[206] & ~part84))
let part85 = (((~v[111] & v[198]) ^ v[13]))
input[168] = (((~v[111] & v[198]) ^ v[103]) ^ (v[206] & ~part85))
input[54] = v[195]
v[207] = input[122]
let part86 = ((v[103] | v[111]))
input[132] = (part86 ^ v[13])
v[208] = (v[186] & ~v[207])
v[209] = input[122]
let part87 = ((~v[111] ^ v[13]))
input[141] = (((part87 & v[103]) & v[206]) ^ v[204])
input[68] = v[208]
v[210] = (v[36] | (v[209] ^ v[208]))
input[194] = ((v[206] & ~v[204]) ^ v[111])
v[211] = (v[195] & ~v[100])
v[212] = (v[195] & v[100])
v[213] = (v[195] & ~v[101])
v[214] = input[62]
input[105] = v[210]
v[215] = (v[205] | v[214])
v[216] = input[31]
input[153] = v[213]
input[185] = v[211]
v[217] = v[216]
v[218] = (v[105] ^ v[216])
v[219] = input[80]
input[64] = v[212]
v[220] = (v[218] | v[219])
v[221] = v[205]
v[222] = input[178]
input[32] = v[205]
let part88 = ((v[220] ^ v[217]))
v[223] = (v[222] & ~part88)
v[224] = input[74]
v[225] = ~v[205]
v[226] = input[200]
v[227] = (((input[24] & v[205]) & v[78]) ^ v[215])
input[4] = v[218]
v[228] = (v[227] & v[192])
v[229] = input[77]
v[230] = (v[102] & input[61])
v[231] = input[84]
let part89 = (((v[173] ^ v[218]) | input[23]))
v[232] = ((v[167] ^ v[223]) ^ part89)
input[176] = v[215]
v[233] = ((v[141] ^ v[231]) ^ v[169])
v[234] = (v[221] | input[69])
v[235] = (v[221] | v[226])
input[117] = (v[218] ^ v[175])
v[236] = (v[201] & input[178])
v[237] = ((v[225] & v[229]) ^ input[24])
let part90 = ((v[187] ^ input[47]))
v[238] = (part90 & v[3])
let part91 = ((v[230] ^ input[136]))
v[239] = (v[233] ^ (part91 & input[1]))
v[240] = (v[221] | v[224])
v[241] = ((input[39] ^ input[13]) ^ v[221])
v[242] = (v[18] & ~input[24])
input[74] = (v[225] & v[224])
v[243] = (v[232] & input[7])
let part92 = (((v[225] & v[224]) ^ v[101]))
v[244] = (part92 & v[192])
let part93 = ((v[234] | v[78]))
v[245] = ((v[225] & v[224]) ^ part93)
let part94 = ((v[234] ^ v[224]))
v[246] = (part94 & ~v[78])
v[247] = (v[215] ^ v[224])
v[248] = input[31]
input[152] = v[245]
v[249] = v[246]
let part95 = ((v[221] | v[226]))
let part96 = ((part95 ^ v[226]))
let part97 = (((part96 & v[192]) ^ v[245]))
v[250] = ((part97 & v[32]) ^ v[248])
v[251] = ((v[215] & v[78]) ^ v[237])
v[252] = v[250]
v[253] = (v[237] | v[78])
v[254] = (v[215] ^ input[106])
v[255] = ((v[235] ^ input[62]) | v[78])
let part98 = ((v[251] ^ (v[192] & ~v[235])))
v[256] = (v[32] & ~part98)
v[257] = input[62]
input[94] = v[251]
input[100] = v[254]
v[258] = (v[225] & v[257])
input[200] = v[247]
v[259] = ((v[225] & input[39]) ^ v[257])
v[260] = input[10]
v[261] = (v[259] ^ v[253])
v[262] = (v[253] ^ v[229])
input[120] = v[262]
v[263] = (v[260] ^ input[18])
input[77] = (v[228] ^ v[262])
v[264] = ((v[228] ^ v[262]) ^ v[256])
v[265] = (v[261] & v[192])
v[266] = (v[221] | input[24])
v[267] = (v[238] ^ v[81])
v[268] = (((v[105] & input[115]) ^ input[124]) ^ v[184])
v[269] = (v[263] | input[2])
v[270] = v[263]
v[271] = input[39]
v[272] = input[69]
input[52] = ((v[266] ^ input[69]) ^ v[255])
v[273] = ((v[258] ^ v[271]) | v[78])
let part99 = ((v[221] | v[229]))
v[274] = (part99 ^ v[272])
let part100 = ((v[221] | v[271]))
v[275] = ((part100 & ~v[78]) ^ (input[106] & ~v[192]))
v[276] = (~v[18] & input[24])
v[277] = input[199]
v[278] = (v[23] & v[277])
v[279] = (v[242] & v[277])
v[280] = (v[268] | input[63])
v[281] = (v[247] ^ v[273])
v[282] = (((input[27] ^ input[24]) ^ v[258]) ^ v[249])
v[283] = v[221]
let part101 = ((v[240] ^ v[272]))
v[284] = ((part101 & ~v[78]) ^ v[254])
let part102 = ((v[20] | ~v[18]))
v[285] = (input[199] & part102)
let part103 = (((v[240] ^ v[229]) | v[78]))
let part104 = ((((v[225] & input[106]) ^ input[82]) ^ part103))
v[286] = (v[192] & ~part104)
let part105 = (((v[23] & v[277]) ^ v[276]))
v[287] = ((v[221] & part105) ^ v[37])
v[288] = ((v[241] ^ (v[274] & ~v[78])) ^ (v[32] & ~v[275]))
let part106 = (((v[20] ^ (v[242] & v[277])) | v[221]))
v[289] = (part106 ^ v[18])
v[290] = input[41]
let part107 = ((v[21] & ~v[18]))
v[291] = ((~part107 & input[199]) ^ v[23])
let part108 = ((v[244] ^ input[52]))
input[112] = ((v[282] ^ v[265]) ^ (v[32] & ~part108))
v[292] = (v[239] ^ v[280])
v[293] = (v[288] ^ (v[192] & ~v[284]))
v[294] = (~v[21] & input[199])
v[295] = ((v[285] ^ (v[21] & ~v[18])) ^ (v[283] & v[20]))
v[296] = (v[286] ^ v[281])
input[170] = v[296]
v[297] = (v[291] ^ v[283])
v[298] = v[289]
v[299] = v[283]
v[300] = (v[283] & v[21])
v[301] = v[264]
v[302] = v[293]
v[303] = (v[252] ^ v[296])
input[106] = v[281]
input[41] = (v[290] ^ v[301])
input[13] = v[302]
input[84] = v[292]
let part109 = ((v[287] | v[87]))
v[304] = (part109 ^ v[297])
let part110 = ((v[298] | v[87]))
v[305] = (v[295] ^ part110)
v[306] = v[303]
input[102] = v[303]
v[307] = (v[10] | input[103])
v[308] = ((v[300] ^ v[294]) ^ v[23])
input[99] = v[308]
v[309] = input[103]
input[130] = v[297]
input[146] = (v[292] | v[10])
v[310] = ~v[309]
v[311] = ~v[10]
v[312] = (input[117] ^ input[34])
v[313] = input[159]
v[314] = (v[236] ^ v[312])
input[137] = v[304]
let part111 = ((v[292] | v[10]))
v[315] = (part111 & ~v[292])
v[316] = (input[109] ^ v[313])
v[317] = ((v[243] ^ v[236]) ^ v[312])
let part112 = (((~v[10] & v[292]) ^ v[307]))
v[318] = (input[58] & ~part112)
input[174] = v[305]
v[319] = v[318]
v[320] = (v[316] ^ input[43])
v[321] = (v[10] & ~v[309])
v[322] = (input[96] ^ v[317])
v[323] = input[125]
input[69] = (v[10] & v[292])
let part113 = (((v[267] ^ v[270]) | v[323]))
v[324] = ((v[320] ^ v[269]) ^ part113)
let part114 = ((v[10] & v[292]))
v[325] = (v[292] & ~part114)
v[326] = ((v[292] | v[10]) | input[103])
v[327] = (v[325] ^ input[65])
v[328] = (v[22] ^ input[24])
v[329] = (v[292] ^ input[57])
v[330] = (input[103] | v[315])
v[331] = (((v[10] & v[292]) ^ input[7]) ^ v[330])
let part115 = (((v[10] & v[292]) ^ v[307]))
let part116 = ((((part115 & input[58]) ^ v[315]) ^ v[307]))
v[332] = (part116 & v[322])
input[43] = v[324]
let part117 = (((v[292] ^ v[10]) ^ v[321]))
v[333] = (part117 & input[58])
v[334] = ((v[321] & ~v[292]) ^ (v[10] & v[292]))
v[335] = (v[325] ^ v[333])
v[336] = input[103]
input[34] = v[312]
v[337] = ((v[292] ^ v[10]) ^ v[336])
v[338] = ((v[292] ^ v[10]) | v[336])
v[339] = input[115]
input[186] = v[317]
v[340] = (v[337] ^ v[339])
v[341] = input[58]
v[342] = (v[337] | input[58])
input[160] = v[314]
v[343] = (v[307] ^ v[10])
v[344] = (v[307] & v[341])
input[96] = v[322]
let part118 = ((v[292] | input[103]))
v[345] = (part118 ^ v[292])
input[61] = v[334]
v[346] = input[103]
let part119 = ((v[345] ^ v[344]))
v[347] = (v[322] & ~part119)
let part120 = ((v[325] | v[346]))
let part121 = ((v[327] ^ part120))
v[348] = (part121 & v[322])
let part122 = (((v[10] & v[292]) | v[346]))
let part123 = ((v[325] ^ part122))
v[349] = (part123 & input[58])
let part124 = ((v[292] | v[10]))
v[350] = (v[329] ^ (part124 & v[310]))
let part125 = ((v[292] | v[10]))
v[351] = (((v[10] & v[292]) & v[310]) ^ part125)
v[352] = v[331]
let part126 = ((v[342] ^ (v[10] & v[292])))
let part127 = ((v[292] | v[10]))
let part128 = ((v[292] | v[10]))
v[353] = ((((part127 & v[310]) ^ part128) ^ v[349]) ^ (part126 & v[322]))
let part129 = ((v[335] ^ ((v[10] & v[292]) & v[310])))
let part130 = ((v[292] | v[10]))
let part131 = ((part130 ^ v[338]))
v[354] = (((input[58] & ~part131) ^ v[352]) ^ (v[322] & ~part129))
v[355] = input[58]
v[356] = (v[355] & ~v[315])
let part132 = ((v[330] ^ v[315]))
v[357] = ((part132 & v[355]) ^ v[334])
v[358] = input[58]
let part133 = ((v[356] ^ (v[10] & v[292])))
v[359] = (v[322] & ~part133)
v[360] = (v[345] ^ (v[343] & v[358]))
v[361] = input[58]
v[362] = ((v[358] & ~v[343]) ^ input[21])
v[363] = input[58]
input[164] = v[351]
v[364] = (v[330] ^ (v[292] & v[361]))
let part134 = ((v[338] ^ v[292]))
v[365] = (((v[338] ^ v[292]) ^ (v[361] & ~part134)) ^ v[332])
v[366] = ((v[324] & ~input[198]) ^ input[30])
let part135 = (((v[326] ^ v[10]) ^ v[319]))
let part136 = (((v[357] ^ (part135 & v[322])) | v[97]))
v[367] = (((v[350] ^ (v[326] & v[363])) ^ v[359]) ^ part136)
v[368] = input[27]
input[57] = v[367]
let part137 = (((v[360] ^ v[348]) | v[97]))
v[369] = (((v[362] ^ v[351]) ^ v[347]) ^ part137)
let part138 = ((v[326] ^ v[292]))
v[370] = ((v[340] ^ (part138 & v[363])) ^ (v[322] & ~v[364]))
input[198] = (v[366] | v[368])
v[371] = (v[302] | v[369])
input[21] = v[369]
v[372] = (v[370] ^ (v[365] & ~v[97]))
input[115] = v[372]
input[65] = (v[302] | v[369])
v[373] = (v[354] ^ (v[353] & ~v[97]))
v[374] = (v[285] ^ v[20])
v[375] = input[119]
input[7] = v[373]
v[376] = (v[328] & v[225])
v[377] = input[139]
v[378] = input[135]
input[180] = v[371]
v[379] = ((v[324] & v[377]) ^ v[378])
v[380] = (v[278] ^ v[18])
let part139 = (((v[324] & input[188]) | input[27]))
v[381] = (((input[20] ^ input[92]) ^ (v[324] & ~input[158])) ^ part139)
v[382] = (v[10] | v[381])
v[383] = (v[10] & v[381])
let part140 = ((v[10] ^ v[381]))
v[384] = (part140 & v[36])
v[385] = ((((v[10] & v[381]) & v[36]) ^ v[10]) ^ v[381])
let part141 = ((v[10] | v[381]))
v[386] = (part141 & v[36])
v[387] = ((v[384] ^ v[10]) ^ v[381])
let part142 = ((v[10] | v[381]))
v[388] = (v[36] & ~part142)
v[389] = ((v[384] ^ v[10]) | v[186])
v[390] = (v[186] | (v[10] ^ v[381]))
v[391] = ((v[10] & ~v[381]) ^ v[386])
let part143 = ((v[10] | v[381]))
v[392] = ((v[36] & ~part143) ^ v[10])
v[393] = ~input[27]
let part144 = ((((v[299] & ~v[18]) ^ v[38]) | v[87]))
let part145 = ((v[28] ^ v[18]))
v[394] = (((v[299] & ~part145) ^ v[374]) ^ part144)
v[395] = (input[58] | v[116])
v[396] = (v[186] | ((v[384] ^ v[10]) ^ v[381]))
v[397] = (((input[56] ^ input[183]) ^ (v[324] & ~input[15])) ^ (v[379] & v[393]))
let part146 = ((v[391] ^ v[390]))
v[398] = (((v[386] ^ v[381]) ^ (~v[186] & v[385])) ^ (v[92] & ~part146))
v[399] = (v[113] & v[106])
let part147 = ((v[389] ^ v[384]))
v[400] = ((v[392] ^ v[396]) ^ (part147 & v[92]))
v[401] = ((v[113] & v[106]) ^ v[113])
v[402] = (v[400] ^ input[63])
let part148 = ((v[21] & ~v[18]))
let part149 = (((v[376] ^ v[38]) | v[87]))
v[403] = ((((part149 ^ input[1]) ^ v[380]) ^ (v[299] & ~part148)) ^ (v[397] & ~v[394]))
v[404] = (input[58] ^ v[115])
v[405] = (v[382] ^ v[388])
v[406] = (v[402] ^ (v[292] & ~v[398]))
let part150 = ((((v[36] & ~v[383]) ^ v[381]) ^ v[390]))
v[407] = (((v[405] & ~v[186]) ^ v[383]) ^ (part150 & v[92]))
let part151 = ((v[395] ^ v[18]))
let part152 = ((((v[97] & ~part151) ^ v[113]) ^ (v[18] & v[106])))
v[408] = ((((v[401] & ~v[97]) ^ v[113]) ^ (v[18] & v[106])) ^ (part152 & v[98]))
let part153 = ((v[406] & v[403]))
v[409] = (v[403] & ~part153)
let part154 = ((v[408] | v[397]))
let part155 = ((v[395] ^ v[18]))
let part156 = (((part155 & v[97]) ^ v[18]))
let part157 = ((v[401] | v[97]))
v[410] = ((((part157 ^ v[404]) ^ v[105]) ^ (part156 & v[98])) ^ part154)
v[411] = (v[402] ^ (v[292] & ~v[398]))
let part158 = ((v[384] ^ v[381]))
let part159 = (((part158 & ~v[186]) ^ v[387]))
let part160 = ((v[186] | v[381]))
v[412] = ((((v[311] & v[381]) ^ v[386]) ^ part160) ^ (v[92] & ~part159))
v[413] = ((v[400] ^ input[53]) ^ (v[398] & ~v[292]))
v[414] = (v[411] | v[403])
v[415] = (v[411] ^ v[403])
let part161 = ((v[406] & v[403]))
v[416] = ((v[403] & ~part161) | v[372])
let part162 = ((v[411] | v[403]))
v[417] = (part162 & ~v[372])
v[418] = ((v[407] & ~v[292]) ^ v[412])
let part163 = ((v[411] ^ v[403]))
v[419] = (part163 & ~v[372])
let part164 = ((v[411] | v[403]))
v[420] = (v[416] ^ part164)
v[421] = (v[292] & ~v[407])
v[422] = (v[373] & ~v[413])
v[423] = (v[412] ^ input[35])
input[42] = v[410]
v[424] = input[196]
input[20] = v[381]
input[1] = v[403]
input[53] = v[413]
input[119] = (v[413] ^ v[373])
input[56] = v[397]
input[66] = v[422]
input[63] = v[406]
input[92] = (v[373] & ~v[422])
input[196] = (v[418] ^ v[424])
input[35] = (v[423] ^ v[421])
input[2] = (v[413] | v[373])
input[124] = (v[306] ^ v[410])
input[159] = (v[413] & v[373])
input[15] = (v[410] & v[306])
input[10] = (v[413] & ~v[373])
input[145] = (~v[410] & v[306])
input[139] = (~v[306] & v[410])
let part165 = ((v[410] & v[306]))
input[183] = (v[410] & ~part165)
let part166 = ((v[306] | v[410]))
input[135] = (part166 & ~v[410])
input[93] = (((v[306] & v[372]) ^ v[414]) ^ v[417])
v[425] = (~v[372] & v[403])
input[125] = ((v[419] ^ v[406]) ^ (v[306] & ~v[417]))
input[162] = (v[406] & v[403])
let part167 = ((v[403] | v[372]))
let part168 = ((v[403] | v[372]))
let part169 = ((v[406] & v[403]))
let part170 = (((v[403] & ~part169) ^ part167))
input[79] = ((part170 & v[306]) ^ part168)
v[426] = input[90]
input[47] = v[425]
let part171 = ((v[406] & v[403]))
input[75] = (v[403] & ~part171)
input[158] = (v[306] | v[410])
v[427] = input[201]
let part172 = ((v[406] | v[372]))
input[136] = ((v[415] ^ part172) ^ (v[306] & ~v[420]))
v[428] = (((v[299] & ~v[23]) ^ v[279]) ^ v[21])
let part173 = (((~v[97] & v[114]) ^ input[58]))
v[429] = (part173 & v[98])
let part174 = (((v[324] & ~v[426]) ^ input[78]))
v[430] = (((v[375] ^ input[6]) ^ (v[324] & v[427])) ^ (part174 & v[393]))
v[431] = (((v[299] & v[242]) ^ v[41]) | v[87])
let part175 = (((v[266] ^ v[242]) | v[87]))
v[432] = (((v[299] & ~v[21]) ^ v[27]) ^ part175)
v[433] = ((v[428] & ~v[87]) ^ ((v[276] & ~input[199]) & v[299]))
let part176 = ((input[24] ^ v[27]))
let part177 = (((v[299] & ~part176) ^ v[21]))
v[434] = (part177 & ~v[87])
v[435] = (v[13] | v[103])
input[70] = (v[403] & ~v[406])
v[436] = ((v[308] ^ input[178]) ^ v[434])
let part178 = ((v[395] ^ v[116]))
let part179 = (((v[18] ^ (v[18] & v[106])) ^ (part178 & v[97])))
v[437] = (((v[117] ^ v[109]) ^ (v[97] & ~v[109])) ^ (part179 & v[98]))
v[438] = ((v[13] | v[103]) | v[111])
v[439] = input[70]
input[126] = (~v[403] & v[406])
v[440] = (v[439] & ~v[372])
v[441] = input[122]
input[201] = (v[430] ^ input[122])
v[442] = (v[104] ^ input[38])
let part180 = ((v[118] ^ v[115]))
let part181 = (((v[97] & ~v[404]) ^ v[399]))
v[443] = (((part181 & v[98]) ^ (v[109] & v[106])) ^ (v[97] & ~part180))
let part182 = ((v[117] ^ v[112]))
let part183 = (((v[429] ^ (v[109] & v[106])) ^ (v[97] & ~part182)))
v[444] = (part183 & ~v[397])
v[445] = (v[438] ^ v[435])
v[446] = ((v[414] & ~v[403]) | v[372])
v[447] = (input[126] ^ v[425])
v[448] = input[122]
v[449] = ((v[186] & v[441]) ^ input[201])
input[192] = ((v[430] & ~v[186]) & ~v[36])
input[148] = (~v[430] & v[448])
v[450] = (v[442] ^ v[126])
let part184 = ((v[437] | v[397]))
v[451] = (part184 ^ v[147])
let part185 = ((v[431] ^ v[49]))
input[26] = (v[304] ^ (part185 & v[397]))
input[178] = (v[436] ^ (v[397] & ~v[432]))
v[452] = ((v[397] & ~v[433]) ^ v[305])
let part186 = ((v[443] | v[397]))
v[453] = ((v[144] ^ v[324]) ^ part186)
v[454] = ((v[142] ^ v[5]) ^ v[444])
let part187 = ((v[409] ^ v[419]))
v[455] = (v[306] & ~part187)
v[456] = (v[409] ^ v[440])
let part188 = ((v[414] | v[372]))
v[457] = (input[126] ^ part188)
v[458] = (input[126] & v[306])
v[459] = (input[126] & ~v[306])
v[460] = (v[449] ^ input[192])
v[461] = (v[186] & input[148])
v[462] = input[26]
input[25] = (v[451] ^ v[34])
v[463] = input[178]
v[464] = v[461]
v[465] = v[462]
input[193] = (v[454] & v[373])
v[466] = input[37]
input[173] = v[454]
input[149] = v[453]
input[49] = (~v[306] & v[463])
input[107] = v[451]
input[37] = (v[466] ^ v[465])
input[150] = v[452]
let part189 = ((v[445] | v[430]))
input[129] = (part189 ^ v[450])
input[155] = ((v[446] ^ (v[406] & v[403])) ^ v[455])
let part190 = (((v[406] & v[403]) ^ v[416]))
input[182] = ((v[417] ^ v[415]) ^ (v[306] & ~part190))
let part191 = ((v[417] ^ v[403]))
input[188] = ((((~v[372] & v[406]) & v[403]) ^ v[403]) ^ (part191 & v[306]))
input[6] = v[430]
let part192 = ((v[403] | v[372]))
let part193 = ((part192 ^ v[406]))
input[86] = ((v[406] ^ v[416]) ^ (part193 & ~v[306]))
let part194 = ((v[403] | v[372]))
let part195 = ((v[414] ^ part194))
input[39] = ((part195 & v[306]) ^ (v[406] & v[403]))
v[467] = input[87]
input[109] = (v[414] ^ v[403])
let part196 = ((v[440] ^ (v[406] & v[403])))
input[142] = ((v[446] ^ v[403]) ^ (v[306] & ~part196))
v[468] = ((v[186] & ~v[430]) ^ input[122])
input[45] = ((v[406] ^ v[416]) ^ v[306])
let part197 = ((v[414] ^ v[440]))
input[97] = (v[456] ^ (v[306] & ~part197))
let part198 = ((v[414] | v[372]))
let part199 = ((part198 ^ (v[406] & v[403])))
input[30] = (v[457] ^ (part199 & v[306]))
input[18] = (v[458] ^ v[425])
input[31] = ((~v[306] & v[447]) ^ v[425])
input[71] = (~v[372] & v[459])
input[87] = (v[467] ^ v[452])
input[27] = (v[186] ^ v[430])
input[78] = (v[460] & v[190])
input[90] = (v[464] ^ v[430])
input[50] = v[468]
}
}
| mit | 8c821197a751cc70a38d3614414ff9e7 | 39.718193 | 118 | 0.398435 | 2.450376 | false | false | false | false |
apple/swift | test/DebugInfo/shadowcopy-linetable.swift | 36 | 972 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
func markUsed<T>(_ t: T) {}
func foo(_ x: inout Int64) {
// Make sure the shadow copy is being made in the prologue or (at
// line 0), but the code to load the value from the inout storage is
// not.
// CHECK: %[[X:.*]] = alloca %Ts5Int64V*, align {{(4|8)}}
// CHECK-NEXT: call void @llvm.dbg.declare
// CHECK-NEXT: %[[ZEROED:[0-9]+]] = bitcast %Ts5Int64V** %[[X]] to i8*{{$}}
// CHECK-NEXT: call void @llvm.memset.{{.*}}(i8* align {{(4|8)}} %[[ZEROED]], i8 0
// CHECK: store %Ts5Int64V* %0, %Ts5Int64V** %[[X]], align {{(4|8)}}
// CHECK-SAME: !dbg ![[LOC0:.*]]
// CHECK-NEXT: getelementptr inbounds %Ts5Int64V, %Ts5Int64V* %0, i32 0, i32 0,
// CHECK-SAME: !dbg ![[LOC1:.*]]
// CHECK: ![[LOC0]] = !DILocation(line: 0,
// CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+1]],
x = x + 2
}
func main() {
var x : Int64 = 1
foo(&x)
markUsed("break here to see \(x)")
}
main()
| apache-2.0 | a72bd52488f594c43b1fc8fc5703aeb3 | 33.714286 | 84 | 0.563786 | 2.7851 | false | false | false | false |
vector-im/vector-ios | Config/CommonConfiguration.swift | 1 | 4216 | //
// Copyright 2020 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MatrixSDK
/// CommonConfiguration is the central point to setup settings for MatrixSDK, MatrixKit and common configurations for all targets.
class CommonConfiguration: NSObject, Configurable {
// MARK: - Global settings
func setupSettings() {
setupMatrixKitSettings()
setupMatrixSDKSettings()
}
private func setupMatrixKitSettings() {
guard let settings = MXKAppSettings.standard() else {
return
}
// Disable CallKit
settings.isCallKitEnabled = false
// Enable lazy loading
settings.syncWithLazyLoadOfRoomMembers = true
// Customize the default notification content
settings.notificationBodyLocalizationKey = "NOTIFICATION"
settings.messageDetailsAllowSharing = BuildSettings.messageDetailsAllowShare
settings.messageDetailsAllowSaving = BuildSettings.messageDetailsAllowSave
settings.messageDetailsAllowCopyingMedia = BuildSettings.messageDetailsAllowCopyMedia
settings.messageDetailsAllowPastingMedia = BuildSettings.messageDetailsAllowPasteMedia
// Enable link detection if url preview are enabled
settings.enableBubbleComponentLinkDetection = true
MXKContactManager.shared().allowLocalContactsAccess = BuildSettings.allowLocalContactsAccess
}
private func setupMatrixSDKSettings() {
let sdkOptions = MXSDKOptions.sharedInstance()
sdkOptions.applicationGroupIdentifier = BuildSettings.applicationGroupIdentifier
// Define the media cache version
sdkOptions.mediaCacheAppVersion = 0
// Enable e2e encryption for newly created MXSession
sdkOptions.enableCryptoWhenStartingMXSession = true
// Disable identicon use
sdkOptions.disableIdenticonUseForUserAvatar = true
// Pass httpAdditionalHeaders to the SDK
sdkOptions.httpAdditionalHeaders = BuildSettings.httpAdditionalHeaders
// Disable key backup on common
sdkOptions.enableKeyBackupWhenStartingMXCrypto = false
// Pass threading option to the SDK
sdkOptions.enableThreads = RiotSettings.shared.enableThreads
sdkOptions.clientPermalinkBaseUrl = BuildSettings.clientPermalinkBaseUrl
sdkOptions.authEnableRefreshTokens = BuildSettings.authEnableRefreshTokens
// Configure key provider delegate
MXKeyProvider.sharedInstance().delegate = EncryptionKeyManager.shared
}
// MARK: - Per matrix session settings
func setupSettings(for matrixSession: MXSession) {
setupCallsSettings(for: matrixSession)
}
private func setupCallsSettings(for matrixSession: MXSession) {
guard let callManager = matrixSession.callManager else {
// This means nothing happens if the project does not embed a VoIP stack
return
}
// Let's call invite be valid for 1 minute
callManager.inviteLifetime = 60000
if RiotSettings.shared.allowStunServerFallback, let stunServerFallback = BuildSettings.stunServerFallbackUrlString {
callManager.fallbackSTUNServer = stunServerFallback
}
}
// MARK: - Per loaded matrix session settings
func setupSettingsWhenLoaded(for matrixSession: MXSession) {
// Do not warn for unknown devices. We have cross-signing now
matrixSession.crypto.warnOnUnknowDevices = false
}
}
| apache-2.0 | 85b2bee54c604fdd28a0537c40a39276 | 35.982456 | 130 | 0.698529 | 5.511111 | false | false | false | false |
badoo/Chatto | ChattoAdditions/sources/Chat Items/TextMessages/TextMessageViewModel.swift | 1 | 2926 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public protocol TextMessageViewModelProtocol: DecoratedMessageViewModelProtocol {
var text: String { get }
var cellAccessibilityIdentifier: String { get }
var bubbleAccessibilityIdentifier: String { get }
}
open class TextMessageViewModel<TextMessageModelT: TextMessageModelProtocol>: TextMessageViewModelProtocol {
open var text: String {
return self.textMessage.text
}
public let textMessage: TextMessageModelT
public let messageViewModel: MessageViewModelProtocol
public let cellAccessibilityIdentifier = "chatto.message.text.cell"
public let bubbleAccessibilityIdentifier = "chatto.message.text.bubble"
public init(textMessage: TextMessageModelT, messageViewModel: MessageViewModelProtocol) {
self.textMessage = textMessage
self.messageViewModel = messageViewModel
}
open func willBeShown() {
// Need to declare empty. Otherwise subclass code won't execute (as of Xcode 7.2)
}
open func wasHidden() {
// Need to declare empty. Otherwise subclass code won't execute (as of Xcode 7.2)
}
}
open class TextMessageViewModelDefaultBuilder<TextMessageModelT: TextMessageModelProtocol>: ViewModelBuilderProtocol {
public init() {}
let messageViewModelBuilder = MessageViewModelDefaultBuilder()
open func createViewModel(_ textMessage: TextMessageModelT) -> TextMessageViewModel<TextMessageModelT> {
let messageViewModel = self.messageViewModelBuilder.createMessageViewModel(textMessage)
let textMessageViewModel = TextMessageViewModel(textMessage: textMessage, messageViewModel: messageViewModel)
return textMessageViewModel
}
open func canCreateViewModel(fromModel model: Any) -> Bool {
return model is TextMessageModelT
}
}
| mit | 6fffaf329f223dbce164a65c5fe349f5 | 40.8 | 118 | 0.769651 | 5.062284 | false | false | false | false |
Danappelxx/SwiftMongoDB | Sources/Database.swift | 1 | 4701 | //
// Database.swift
// SwiftMongoDB
//
// Created by Dan Appel on 11/23/15.
// Copyright © 2015 Dan Appel. All rights reserved.
//
import CMongoC
import BinaryJSON
public final class Database {
let pointer: _mongoc_database
/// Databases are automatically created on the MongoDB server upon insertion of the first document into a collection. There is no need to create a database manually.
public init(client: Client, name: String) {
self.pointer = mongoc_client_get_database(client.pointer, name)
}
deinit {
mongoc_database_destroy(pointer)
}
public var name: String {
let nameRaw = mongoc_database_get_name(pointer)
return String(cString:nameRaw)
}
public var collectionNames: [String]? {
var error = bson_error_t()
var buffer = mongoc_database_get_collection_names(self.pointer, &error)
if error.error.isError {
return nil
}
var names = [String]()
while buffer.pointee != nil {
let name = String(cString:buffer.pointee)
names.append(name)
buffer = buffer.successor()
}
return names
}
public func removeUser(username: String) throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_remove_user(pointer, username, &error)
try error.throwIfError()
return successful
}
public func removeAllUsers() throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_remove_all_users(pointer, &error)
try error.throwIfError()
return successful
}
// public func addUser(username username: String, password: String, roles: [String], customData: BSON.Document) throws -> Bool {
//
// guard let rolesJSON = roles.toJSON()?.toString() else { throw MongoError.InvalidData }
//
// var error = bson_error_t()
//
// var rolesRaw = try MongoBSON(json: rolesJSON).bson
// var customDataRaw = try MongoBSON(data: customData).bson
//
// let successful = mongoc_database_add_user(pointer, username, password, &rolesRaw, &customDataRaw, &error)
//
// try error.throwIfError()
//
// return successful
// }
// public func command(command: BSON.Document, flags: QueryFlags = .None, skip: Int = 0, limit: Int = 0, batchSize: Int = 0, fields: [String] = []) throws -> Cursor {
//
// guard let fieldsJSON = fields.toJSON()?.toString() else { throw MongoError.InvalidData }
//
// var commandRaw = try MongoBSON(data: command).bson
// var fieldsRaw = try MongoBSON(json: fieldsJSON).bson
//
// let cursorRaw = mongoc_database_command(pointer, flags.rawFlag, skip.UInt32Value, limit.UInt32Value, batchSize.UInt32Value, &commandRaw, &fieldsRaw, nil)
//
// let cursor = Cursor(cursor: cursorRaw)
//
// return cursor
// }
public func drop() throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_drop(pointer, &error)
try error.throwIfError()
return successful
}
public func hasCollection(name name: String) throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_has_collection(pointer, name, &error)
try error.throwIfError()
return successful
}
public func createCollection(name name: String, options: BSON.Document) throws -> Collection {
let options = try BSON.AutoReleasingCarrier(document: options)
var error = bson_error_t()
mongoc_database_create_collection(pointer, name, options.pointer, &error)
try error.throwIfError()
let collection = Collection(database: self, name: name)
return collection
}
public func findCollections(filter filter: BSON.Document) throws -> Cursor {
let filter = try BSON.AutoReleasingCarrier(document: filter)
var error = bson_error_t()
let cursorPointer = mongoc_database_find_collections(pointer, filter.pointer, &error)
try error.throwIfError()
let cursor = Cursor(pointer: cursorPointer)
return cursor
}
public func basicCommand(command command: BSON.Document) throws -> BSON.Document {
let command = try BSON.AutoReleasingCarrier(document: command)
var reply = bson_t()
var error = bson_error_t()
mongoc_database_command_simple(self.pointer, command.pointer, nil, &reply, &error)
try error.throwIfError()
guard let res = BSON.documentFromUnsafePointer(&reply) else {
throw MongoError.CorruptDocument
}
return res
}
}
| mit | 8a9fbba36d006ee229b57898008e8109 | 27.143713 | 169 | 0.639149 | 3.966245 | false | false | false | false |
jeannustre/HomeComics | HomeComics/BookDetailViewController.swift | 1 | 2688 | //
// BookDetailViewController.swift
// HomeComics
//
// Created by Jean Sarda on 07/05/2017.
// Copyright © 2017 Jean Sarda. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireObjectMapper
import Alertift
class BookDetailViewController: UIViewController {
@IBOutlet var background: UIImageView!
@IBOutlet var scrollView: UIScrollView!
var book: Book?
var bookLocation: String?
var urls: [URL] = []
let defaults = UserDefaults.standard
func startReading(sender: UIBarButtonItem?) {
if let contents = book?.contents {
for page in contents {
let pageURL = defaults.string(forKey: "cdnBaseURL")! + page
let finalURL = pageURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
urls.append(URL(string: finalURL!)!)
}
performSegue(withIdentifier: "startReading", sender: nil)
} else {
// show alert
Alertift.alert(title: "Error", message: "Book has no contents field")
.action(.default("😔"))
.show(on: self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let readButton = UIBarButtonItem(title: "Read", style: .plain, target: self, action: #selector(startReading(sender:)))
navigationItem.setRightBarButton(readButton, animated: false)
if let id = book?.id {
self.getBookContents(id: id)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "startReading" {
let comicPageViewController = segue.destination as! ReaderViewController
comicPageViewController.pagesIndex = self.urls
}
}
// MARK: - Private
private func getBookContents(id: Int) {
var url = defaults.string(forKey: "serverBaseURL")
url = url! + "/book/\(id)"
let finalURL = url?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
print("Requesting book contents on url : <\(String(describing: finalURL))>")
Alamofire.request(finalURL!).responseObject { (response: DataResponse<Book>) in
let book = response.result.value
if let book = book {
print("Received book contents!")
self.book = book
} else {
// TODO: Couldn't fetch book contents, warn user
}
}
}
}
| gpl-3.0 | c34451f853550b1dbee6fb65d3103485 | 31.731707 | 126 | 0.609165 | 4.94291 | false | false | false | false |
richardpiazza/XCServerCoreData | Example/Pods/CodeQuickKit/Sources/Environment.swift | 2 | 3014 | import Foundation
public struct Environment {
public static var platform: Platform {
return Platform.current
}
public static var architecture: Architecture {
return Architecture.current
}
public static var release: Release {
return Release.current
}
public static var targetEnvironment: TargetEnvironment {
return TargetEnvironment.current
}
}
/// The supported Swift compilation OSs
public enum Platform {
case other
case macOS
case iOS
case watchOS
case tvOS
case linux
case freeBSD
case android
case windows
case ps4
public static var current: Platform {
#if os(macOS)
return .macOS
#elseif os(iOS)
return .iOS
#elseif os(watchOS)
return .watchOS
#elseif os(tvOS)
return .tvOS
#elseif os(Linux)
return .linux
#elseif os(FreeBSD)
return .freeBSD
#elseif os(Android)
return .android
#elseif os(Windows)
return .windows
#elseif os(PS4)
return .ps4
#else
return .other
#endif
}
}
/// The supported Swift compilation architectures
public enum Architecture {
case other
case arm
case arm64
case i386
case x86_64
case powerpc64
case powerpc64le
case s390x
public static var current: Architecture {
#if arch(arm)
return .arm
#elseif arch(arm64)
return .arm64
#elseif arch(i386)
return .i386
#elseif arch(x86_64)
return .x86_64
#elseif arch(powerpc64)
return .powerpc64
#elseif arch(powerpc64le)
return .powerpc64le
#elseif arch(s390x)
return .s390x
#else
return .other
#endif
}
}
/// Recent Swift milestone releases
public enum Release {
case other
case swift2_2
case swift2_3
case swift3_0
case swift3_1
case swift3_2
case swift4_0
case swift4_1
case swift5_0
public static var current: Release {
#if swift(>=5.0)
return .swift5_0
#elseif swift(>=4.1)
return .swift4_1
#elseif swift(>=4.0)
return .swift4_0
#elseif swift(>=3.2)
return .swift3_2
#elseif swift(>=3.1)
return .swift3_1
#elseif swift(>=3.0)
return .swift3_0
#elseif swift(>=2.3)
return .swift2_3
#elseif swift(>=2.2)
return .swift2_2
#else
return .other
#endif
}
}
/// Target Environment; i.e Simulator/Device
public enum TargetEnvironment {
case simulator
case device
public static var current: TargetEnvironment {
#if targetEnvironment(simulator)
return .simulator
#else
return .device
#endif
}
}
| mit | e3a49978f68d1651f4aafd0c518677fe | 20.84058 | 60 | 0.551758 | 4.432353 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ShortcutListController.swift | 1 | 10948 | //
// ShortcutListController.swift
// Telegram
//
// Created by Mikhail Filimonov on 11.02.2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
private func shortcutEntires() -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
// chat
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerChat), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("chat_open_info"), data: InputDataGeneralData(name: strings().shortcutsControllerChatOpenInfo, color: theme.colors.text, icon: nil, type: .context("→"), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("reply_to_message"), data: InputDataGeneralData(name: strings().shortcutsControllerChatSelectMessageToReply, color: theme.colors.text, icon: nil, type: .context("⌘↑ / ⌘↓"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("edit_message"), data: InputDataGeneralData(name: strings().shortcutsControllerChatEditLastMessage, color: theme.colors.text, icon: nil, type: .context("↑"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("edit_media"), data: InputDataGeneralData(name: strings().shortcutsControllerChatRecordVoiceMessage, color: theme.colors.text, icon: nil, type: .context("⌘R"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("search_in_chat"), data: InputDataGeneralData(name: strings().shortcutsControllerChatSearchMessages, color: theme.colors.text, icon: nil, type: .context("⌘F"), viewType: .lastItem, enabled: true, description: nil)))
index += 1
// video chat
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerVideoChat), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("toggle_camera"), data: InputDataGeneralData(name: strings().shortcutsControllerVideoChatToggleCamera, color: theme.colors.text, icon: nil, type: .context("⌘E"), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("toggle_screen"), data: InputDataGeneralData(name: strings().shortcutsControllerVideoChatToggleScreencast, color: theme.colors.text, icon: nil, type: .context("⌘T"), viewType: .lastItem, enabled: true, description: nil)))
index += 1
//search
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerSearch), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("quick_search"), data: InputDataGeneralData(name: strings().shortcutsControllerSearchQuickSearch, color: theme.colors.text, icon: nil, type: .context("⌘K"), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("global_search"), data: InputDataGeneralData(name: strings().shortcutsControllerSearchGlobalSearch, color: theme.colors.text, icon: nil, type: .context("⇧⌘F"), viewType: .lastItem, enabled: true, description: nil)))
index += 1
//MARKDOWN
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerMarkdown), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("markdown_bold"), data: InputDataGeneralData(name: strings().shortcutsControllerMarkdownBold, color: theme.colors.text, icon: nil, type: .context("⌘B / **"), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("markdown_italic"), data: InputDataGeneralData(name: strings().shortcutsControllerMarkdownItalic, color: theme.colors.text, icon: nil, type: .context("⌘I / __"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("markdown_monospace"), data: InputDataGeneralData(name: strings().shortcutsControllerMarkdownMonospace, color: theme.colors.text, icon: nil, type: .context("⇧⌘K / `"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("markdown_url"), data: InputDataGeneralData(name: strings().shortcutsControllerMarkdownHyperlink, color: theme.colors.text, icon: nil, type: .context("⌘U"), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("markdown_strikethrough"), data: InputDataGeneralData(name: strings().shortcutsControllerMarkdownStrikethrough, color: theme.colors.text, icon: nil, type: .context("~~"), viewType: .lastItem, enabled: true, description: nil)))
index += 1
// OTHERS
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerOthers), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("lock_passcode"), data: InputDataGeneralData(name: strings().shortcutsControllerOthersLockByPasscode, color: theme.colors.text, icon: nil, type: .context("⌘L"), viewType: .singleItem, enabled: true, description: nil)))
index += 1
// MOUSE
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerMouse), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("fast_reply"), data: InputDataGeneralData(name: strings().shortcutsControllerMouseFastReply, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerMouseFastReplyValue), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("schedule"), data: InputDataGeneralData(name: strings().shortcutsControllerMouseScheduleMessage, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerMouseScheduleMessageValue), viewType: .lastItem, enabled: true, description: nil)))
index += 1
//Trackpad Gesture
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().shortcutsControllerGestures), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("swipe_reply"), data: InputDataGeneralData(name: strings().shortcutsControllerGesturesReply, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerGesturesReplyValue), viewType: .firstItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("swipe_actions"), data: InputDataGeneralData(name: strings().shortcutsControllerGesturesChatAction, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerGesturesChatActionValue), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("swipe_navigation"), data: InputDataGeneralData(name: strings().shortcutsControllerGesturesNavigation, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerGesturesNavigationsValue), viewType: .innerItem, enabled: true, description: nil)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("swipe_stickers"), data: InputDataGeneralData(name: strings().shortcutsControllerGesturesStickers, color: theme.colors.text, icon: nil, type: .context(strings().shortcutsControllerGesturesStickersValue), viewType: .lastItem, enabled: true, description: nil)))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func ShortcutListController(context: AccountContext) -> ViewController {
let controller = InputDataController(dataSignal: .single(InputDataSignalValue(entries: shortcutEntires())), title: strings().shortcutsControllerTitle, validateData: { data in
return .fail(.none)
}, removeAfterDisappear: true, hasDone: false, identifier: "shortcuts")
controller._abolishWhenNavigationSame = true
return controller
}
| gpl-2.0 | 5dca4b7dac695003b53020eb57e49c53 | 65.115152 | 389 | 0.726464 | 4.381124 | false | false | false | false |
inamiy/ReactiveCocoaCatalog | ReactiveCocoaCatalog/Samples/ReactiveArrayViewControllerType.swift | 1 | 13986 | //
// ReactiveArrayViewControllerType.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-05.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import ReactiveObjC
import ReactiveObjCBridge
import ReactiveArray
/// Abstract interface for ReactiveArray demos.
/// **For Demo Use Only.**
protocol ReactiveArrayViewControllerType: class
{
associatedtype ItemsView: UIView, ItemsViewType
var itemsView: ItemsView { get }
weak var insertButtonItem: UIBarButtonItem? { get }
weak var replaceButtonItem: UIBarButtonItem? { get }
weak var removeButtonItem: UIBarButtonItem? { get }
weak var decrementButtonItem: UIBarButtonItem? { get }
weak var incrementButtonItem: UIBarButtonItem? { get }
weak var sectionOrItemButtonItem: UIBarButtonItem? { get }
var viewModel: ReactiveArrayViewModel { get }
var protocolSelectorForDidSelectItem: (Selector, Protocol) { get }
func setupSignalsForDemo()
func playDemo()
}
extension ReactiveArrayViewControllerType where Self: UIViewController
{
func setupSignalsForDemo()
{
guard let insertButtonItem = self.insertButtonItem,
let replaceButtonItem = self.replaceButtonItem,
let removeButtonItem = self.removeButtonItem,
let decrementButtonItem = self.decrementButtonItem,
let incrementButtonItem = self.incrementButtonItem,
let sectionOrItemButtonItem = self.sectionOrItemButtonItem else
{
assertionFailure("Storyboard UIs are not ready.")
return
}
insertButtonItem.reactive.defaultPressed
.withLatest(from: self.viewModel.sectionOrItem.producer)
.map { $1 }
.on(event: logSink("insertButtonItem"))
.observeValues { [unowned self] mode, insertCount in
guard insertCount > 0 else { return }
switch mode {
case .section:
for _ in 1...insertCount {
let sectionCount = self.viewModel.sections.observableCount.value
let randomSection = Section.randomData()
self.viewModel.sections.insert(
randomSection,
at: random(sectionCount + 1)
)
}
case .item:
let sectionCount = self.viewModel.sections.observableCount.value
guard sectionCount > 0 else { break }
for _ in 1...insertCount {
let section = self.viewModel.sections[random(sectionCount)]
let itemCount = section.items.observableCount.value
section.items.insert(
Item.randomData(),
at: random(itemCount + 1)
)
}
}
}
replaceButtonItem.reactive.defaultPressed
.withLatest(from: self.viewModel.sectionOrItem.producer)
.map { $1 }
.on(event: logSink("replaceButtonItem"))
.observeValues { [unowned self] mode, replaceCount in
guard replaceCount > 0 else { return }
switch mode {
case .section:
for _ in 1...replaceCount {
let sectionCount = self.viewModel.sections.observableCount.value
guard sectionCount > 0 else { break }
let randomSection = Section.randomData()
self.viewModel.sections.update(
randomSection,
at: random(sectionCount)
)
}
case .item:
let sectionCount = self.viewModel.sections.observableCount.value
guard sectionCount > 0 else { break }
for _ in 1...replaceCount {
let section = self.viewModel.sections[random(sectionCount)]
let itemCount = section.items.observableCount.value
guard itemCount > 0 else { break }
section.items.update(
Item.randomData(),
at: random(itemCount)
)
}
}
}
removeButtonItem.reactive.defaultPressed
.withLatest(from: self.viewModel.sectionOrItem.producer)
.map { $1 }
.on(event: logSink("removeButtonItem"))
.observeValues { [unowned self] mode, removeCount in
guard removeCount > 0 else { return }
switch mode {
case .section:
for _ in 1...removeCount {
let sectionCount = self.viewModel.sections.observableCount.value
guard sectionCount > 0 else { break }
self.viewModel.sections.remove(at: random(sectionCount))
}
case .item:
let sectionCount = self.viewModel.sections.observableCount.value
guard sectionCount > 0 else { break }
for _ in 1...removeCount {
let section = self.viewModel.sections[random(sectionCount)]
let itemCount = section.items.observableCount.value
guard itemCount > 0 else { break }
section.items.remove(at: random(itemCount))
}
}
}
let decrement = decrementButtonItem.reactive.defaultPressed
.map { _ in -1 }
.on(event: logSink("decrement"))
let increment = incrementButtonItem.reactive.defaultPressed
.map { _ in 1 }
.on(event: logSink("increment"))
let count = decrement.merge(with: increment)
.withLatest(from: self.viewModel.sectionOrItem.producer)
.map { max($1.1 + $0, 1) }
let countProducer = SignalProducer(count)
.prefix(value: 1)
let sectionOrItem = sectionOrItemButtonItem.reactive.defaultPressed
.withLatest(from: self.viewModel.sectionOrItem.producer)
.map { $1.0.inverse }
let sectionOrItemProducer = SignalProducer(sectionOrItem)
.prefix(value: .section)
.on(event: logSink("sectionOrItem"))
decrementButtonItem.reactive.isEnabled
<~ countProducer
.map { $0 > 1 }
//
// Update `viewModel.sectionOrItem`.
//
// NOTE:
// `count` is dependent on current `viewModel.sectionOrItem`,
// so bind to it at last usage of `count`.
//
self.viewModel.sectionOrItem
<~ SignalProducer.combineLatest(sectionOrItemProducer, countProducer)
sectionOrItemButtonItem.reactive.title
<~ self.viewModel.sectionOrItem.producer
.map { "\($0.0.rawValue) \($0.1)" } // e.g. "Section 1"
// Update `tableView` sections.
self.viewModel.changedSectionInfoSignal
.observeValues(_updateSections(itemsView: self.itemsView))
// Update `tableView` rows.
self.viewModel.changedItemInfoSignal
.observeValues(_updateItems(itemsView: self.itemsView))
// Delete item (or section) via `didSelectItem`.
bridgedSignalProducer(from: self.rac_signal(for: protocolSelectorForDidSelectItem.0, from: protocolSelectorForDidSelectItem.1))
.on(event: logSink("didSelectRow"))
.ignoreCastError(NoError.self)
.startWithValues { [weak self] racTuple in
let racTuple = racTuple as! RACTuple
let indexPath = racTuple.second as! NSIndexPath
guard let items = self?.viewModel.sections[indexPath.section].items else {
return
}
if items.count < 2 {
// delete section if last item
self?.viewModel.sections.remove(at: indexPath.section)
}
else {
// delete item
self?.viewModel.sections[indexPath.section].items.remove(at: indexPath.item)
}
}
}
func playDemo()
{
func delay(_ timeInterval: TimeInterval) -> SignalProducer<(), NoError>
{
return SignalProducer.empty
.delay(timeInterval, on: QueueScheduler.main)
}
let t0 = 0.2 // initial delay
let dt = 0.5 // interval
delay(t0)
.on(started: {
print("demo play start")
})
.on(completed: {
print("*** sections.append ***")
self.viewModel.sections.append(
Section(title: "Section 1", items: [
Item(title: "title 1-0"),
Item(title: "title 1-1")
])
)
})
.concat(delay(dt))
.on(completed: {
print("*** sections.insert ***")
self.viewModel.sections.insert(
Section(title: "Section 0", items: [
Item(title: "title 0-0"),
Item(title: "title 0-1"),
Item(title: "title 0-2")
]),
at: 0
)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
print("*** sections.update ***")
self.viewModel.sections.update(
Section(title: "Section 0b", items: [
Item(title: "title 0-0b")
]),
at: 0
)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
print("*** sections.removeAtIndex ***")
self.viewModel.sections.remove(at: 0)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
let section = self.viewModel.sections[0]
print("*** items.append ***")
section.items.append(
Item(title: "title 1-2")
)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
let section = self.viewModel.sections[0]
guard section.items.count > 2 else { return }
print("*** items.insert ***")
section.items.insert(
Item(title: "title 1-1.5"),
at: 2
)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
let section = self.viewModel.sections[0]
guard section.items.count > 2 else { return }
print("*** items.update ***")
section.items.update(
Item(title: "title 1-1.25"),
at: 2
)
})
.concat(delay(dt))
.on(completed: {
guard self.viewModel.sections.count > 0 else { return }
let section = self.viewModel.sections[0]
guard section.items.count > 2 else { return }
print("*** items.removeAtIndex ***")
section.items.remove(at: 2)
})
.on(completed: {
print("demo play end")
})
.start()
}
}
// MARK: Helpers
private func _updateSections<ItemsView: ItemsViewType, Section: SectionType>(itemsView: ItemsView) -> (ChangedSectionInfo<Section>) -> ()
{
return { [unowned itemsView] info in
switch info.sectionOperation {
case .append:
let index = info.sectionCount - 1
itemsView.insertSections([index], animationStyle: .fade)
case let .insert(_, index):
itemsView.insertSections([index], animationStyle: .fade)
case let .update(_, index):
itemsView.reloadSections([index], animationStyle: .fade)
case let .remove(index):
itemsView.deleteSections([index], animationStyle: .fade)
}
}
}
private func _updateItems<ItemsView: ItemsViewType, Item: ItemType>(itemsView: ItemsView) -> (ChangedItemInfo<Item>) -> ()
{
return { [unowned itemsView] info in
switch info.itemOperation {
case .append:
let index = info.itemCount - 1
itemsView.insertItems(at: [IndexPath(row: index, section: info.sectionIndex)], animationStyle: .right)
case let .insert(_, index):
itemsView.insertItems(at: [IndexPath(row: index, section: info.sectionIndex)], animationStyle: .right)
case let .update(_, index):
itemsView.reloadItems(at: [IndexPath(row: index, section: info.sectionIndex)], animationStyle: .right)
case let .remove(index):
itemsView.deleteItems(at: [IndexPath(row: index, section: info.sectionIndex)], animationStyle: .right)
}
}
}
| mit | 8f2b7bf4f05001b69ec7ecd52899a962 | 35.997354 | 137 | 0.512549 | 5.271391 | false | false | false | false |
NikitaAsabin/pdpDecember | DayPhoto/FlipPresentAnimationController.swift | 1 | 2576 | //
// FlipPresentAnimationController.swift
// DayPhoto
//
// Created by Nikita Asabin on 14.01.16.
// Copyright © 2016 Flatstack. All rights reserved.
//
import UIKit
class FlipPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var originFrame = CGRectZero
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.6
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
let containerView = transitionContext.containerView(),
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
let initialFrame = originFrame
let finalFrame = transitionContext.finalFrameForViewController(toVC)
let snapshot = toVC.view.snapshotViewAfterScreenUpdates(true)
snapshot.frame = initialFrame
snapshot.layer.cornerRadius = 25
snapshot.layer.masksToBounds = true
containerView.addSubview(toVC.view)
containerView.addSubview(snapshot)
toVC.view.hidden = true
AnimationHelper.perspectiveTransformForContainerView(containerView)
snapshot.layer.transform = AnimationHelper.yRotation(M_PI_2)
let duration = transitionDuration(transitionContext)
UIView.animateKeyframesWithDuration(
duration,
delay: 0,
options: .CalculationModeCubic,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1/3, animations: {
fromVC.view.layer.transform = AnimationHelper.yRotation(-M_PI_2)
})
UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
snapshot.layer.transform = AnimationHelper.yRotation(0.0)
})
UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
snapshot.frame = finalFrame
})
},
completion: { _ in
toVC.view.hidden = false
snapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
}
}
| mit | 86b48a8b89c4b2904b3fd0670898e5ef | 35.267606 | 108 | 0.633786 | 6.373762 | false | false | false | false |
johnsextro/cycschedule | cycschedule/AppDelegate.swift | 1 | 7726 | import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
let leftNavController = splitViewController.viewControllers.first as! UINavigationController
let masterViewController = leftNavController.topViewController as! MasterViewController
let detailNavController = splitViewController.viewControllers.last as! UINavigationController
let detailViewController = detailNavController.viewControllers.last as! DetailViewController
masterViewController.delegate = detailViewController
detailViewController.navigationItem.leftItemsSupplementBackButton = true
detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
return true
}
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) {
// 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.
}
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) {
// 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) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.xxxx.ProjectName" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyTeams", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("cycschedule.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| gpl-2.0 | 82f70c17059fada86f0a3aabdf517447 | 60.808 | 290 | 0.72612 | 6.348398 | false | false | false | false |
mcjcloud/Show-And-Sell | Show And Sell/Group.swift | 1 | 4039 | //
// Group.swift
// Show And Sell
//
// Created by Brayden Cloud on 10/25/16.
// Copyright © 2016 Brayden Cloud. All rights reserved.
//
import Foundation
class Group: NSObject {
// properties
var groupId: String
var name: String
var adminId: String
var dateCreated: String
var address: String
var routing: String
var latitude: Double
var longitude: Double
var locationDetail: String
var itemsSold: Int // TODO: include this if needed
var rating: Float
init?(data groupJson: Data?) {
if let data = groupJson {
// get the json object
var json: [String: Any]!
do {
json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
}
catch {
return nil
}
// parse the json
if let groupId = json["ssGroupId"] as? String,
let name = json["name"] as? String,
let adminId = json["adminId"] as? String,
let dateCreated = json["dateCreated"] as? String,
let address = json["address"] as? String,
let routing = json["routing"] as? String,
let latitude = json["latitude"] as? Double,
let longitude = json["longitude"] as? Double,
let locationDetail = json["locationDetail"] as? String,
let itemsSold = json["itemsSold"] as? Int,
let rating = json["rating"] as? Float {
self.groupId = groupId
self.name = name
self.adminId = adminId
self.dateCreated = dateCreated
self.address = address
self.routing = routing
self.latitude = latitude
self.longitude = longitude
self.locationDetail = locationDetail
self.itemsSold = itemsSold
self.rating = rating
// init object
super.init()
}
else {
return nil
}
}
else {
return nil
}
}
init(groupId: String, name: String, adminId: String, dateCreated: String, address: String, routing: String, latitude: Double, longitude: Double, locationDetail: String, itemsSold: Int, rating: Float) {
self.groupId = groupId
self.name = name
self.adminId = adminId
self.dateCreated = dateCreated
self.address = address
self.routing = routing
self.latitude = latitude
self.longitude = longitude
self.locationDetail = locationDetail
self.itemsSold = itemsSold
self.rating = rating
}
// group without groupId or date
init(name: String, adminId: String, address: String, routing: String, latitude: Double, longitude: Double, locationDetail: String) {
self.name = name
self.adminId = adminId
self.address = address
self.routing = routing
self.latitude = latitude
self.longitude = longitude
self.locationDetail = locationDetail
self.groupId = ""
self.dateCreated = ""
self.rating = 0.0
self.itemsSold = 0
}
// get Group array from json
static func groupArray(with groupsJson: Data?) -> [Group] {
var result = [Group]()
if let data = groupsJson {
var json: [[String: Any]]!
do {
json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]]
}
catch {
return result
}
for group in json {
if let grp = Group(data: try! JSONSerialization.data(withJSONObject: group)) {
result.append(grp)
}
}
}
// return result
return result
}
}
| apache-2.0 | bf6fe3a1f537163b230eab5528e8cb38 | 30.795276 | 205 | 0.519812 | 5.041199 | false | false | false | false |
loudnate/Loop | LoopCore/Insulin/InsulinModelSettings.swift | 1 | 2389 | //
// InsulinModelSettings.swift
// Loop
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
import LoopKit
public enum InsulinModelSettings {
case exponentialPreset(ExponentialInsulinModelPreset)
case walsh(WalshInsulinModel)
public var model: InsulinModel {
switch self {
case .exponentialPreset(let model):
return model
case .walsh(let model):
return model
}
}
public init?(model: InsulinModel) {
switch model {
case let model as ExponentialInsulinModelPreset:
self = .exponentialPreset(model)
case let model as WalshInsulinModel:
self = .walsh(model)
default:
return nil
}
}
}
extension InsulinModelSettings: CustomDebugStringConvertible {
public var debugDescription: String {
return String(reflecting: model)
}
}
extension InsulinModelSettings: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard let typeName = rawValue["type"] as? InsulinModelType.RawValue,
let type = InsulinModelType(rawValue: typeName)
else {
return nil
}
switch type {
case .exponentialPreset:
guard let modelRaw = rawValue["model"] as? ExponentialInsulinModelPreset.RawValue,
let model = ExponentialInsulinModelPreset(rawValue: modelRaw)
else {
return nil
}
self = .exponentialPreset(model)
case .walsh:
guard let modelRaw = rawValue["model"] as? WalshInsulinModel.RawValue,
let model = WalshInsulinModel(rawValue: modelRaw)
else {
return nil
}
self = .walsh(model)
}
}
public var rawValue: [String : Any] {
switch self {
case .exponentialPreset(let model):
return [
"type": InsulinModelType.exponentialPreset.rawValue,
"model": model.rawValue
]
case .walsh(let model):
return [
"type": InsulinModelType.walsh.rawValue,
"model": model.rawValue
]
}
}
private enum InsulinModelType: String {
case exponentialPreset
case walsh
}
}
| apache-2.0 | 063759272c1b8c79f595ee62d454b363 | 24.677419 | 94 | 0.579146 | 5.070064 | false | false | false | false |
TeamYYZ/DineApp | Dine/PanelIcon.swift | 1 | 2067 | //
// PanelIcon.swift
// Dine
//
// Created by YiHuang on 4/23/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
import ChameleonFramework
class PanelIcon: UIImageView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
let borderView = UIView()
override func layoutSubviews() {
super.layoutSubviews()
// because storyboard has intrinsic width (4s for inferred size), when this view shows on bigger screen, we need to update bounds as well (Maybe it's a bug??)
borderView.frame.size.width = self.frame.size.width
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 24).CGPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
}
override func awakeFromNib() {
// add the shadow to the base view
self.backgroundColor = UIColor.clearColor()
self.layer.shadowColor = UIColor.flatRedColor().CGColor
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowOpacity = 0.8
self.layer.shadowRadius = 3.0
// improve performance
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 24).CGPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
borderView.frame = self.bounds
borderView.layer.cornerRadius = 24
borderView.layer.borderColor = UIColor.flatWhiteColor().CGColor
borderView.layer.borderWidth = 1.0
borderView.layer.masksToBounds = true
self.addSubview(borderView)
let otherSubContent = UIImageView()
otherSubContent.image = UIImage(named: "plate")
otherSubContent.frame = borderView.bounds
borderView.addSubview(otherSubContent)
}
}
| gpl-3.0 | 6b757b091645779e25a51d02dd656884 | 32.322581 | 166 | 0.665053 | 4.804651 | false | false | false | false |
gregomni/swift | test/Generics/opaque_archetype_concrete_requirement_invalid.swift | 3 | 547 | // RUN: %target-swift-frontend -typecheck -verify %s -disable-availability-checking -requirement-machine-inferred-signatures=on -enable-requirement-machine-opaque-archetypes
protocol P1 {}
struct S_P1 : P1 {}
protocol P {
associatedtype T
var t: T { get }
}
struct DefinesOpaqueP1 : P {
var t: some P1 {
return S_P1()
}
}
protocol HasP {
associatedtype T : P1
associatedtype U
}
extension HasP where T == DefinesOpaqueP1.T, U == T.DoesNotExist {}
// expected-error@-1 {{'DoesNotExist' is not a member type of type 'Self.T'}} | apache-2.0 | e55454ab0f2d3b8a667b96a35626d246 | 20.92 | 173 | 0.700183 | 3.440252 | false | false | false | false |
JJMoon/MySwiftCheatSheet | UI_Extension/AnimationUISub/HsEnlargeAni.swift | 1 | 2904 | //
// HsEnlargeAni.swift
// HS Monitor
//
// Created by Jongwoo Moon on 2016. 7. 25..
// Copyright © 2016년 IMLab. All rights reserved.
//
import Foundation
import UIKit
protocol someProtocol {
func sampleFUnc()
}
protocol PrtclEnlargeView {
var targetView: UIView? { get set }
var tarPoint: CGPoint? { get set }
var baseOrigin: CGPoint? { get set }
var scal : CGFloat { get set }
/// 임시로 생성하는 뷰, 버튼
var bgView: UIView? { get set } // 백그라운드의 반투명 버튼
var bttnClose: UIButton? { get set } // 화면 닫는 투명 버튼
var enlargeClsr: ((Void) -> Void)? { get set }
mutating func animation()
}
extension PrtclEnlargeView where Self: UIViewController {
mutating func animation() {
//print(" there here")
if baseOrigin == nil {
print(" Enlarge ")
self.targetView!.contentMode = UIViewContentMode.redraw
baseOrigin = targetView!.center
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 10, initialSpringVelocity: 3,
options: [ ],
animations: {
self.targetView!.center = self.tarPoint!
self.targetView!.transform = CGAffineTransformMakeScale(self.scal, self.scal)})
{ [] (finished: Bool) in
print(" finished >> ")
}
bgView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: UIScreen.mainScreen().bounds.size))
bgView!.backgroundColor = colHalfTransGray
// view.addSubview(bgView!) 백그라운드 뷰 없다....
self.view.bringSubviewToFront(targetView!)
//view.addSubview(bttnClose!)
if (enlargeClsr != nil) { enlargeClsr!() }
} else {
print(" Shrink ")
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 10, initialSpringVelocity: 3,
options: [ ],
animations: {
self.targetView!.transform = CGAffineTransformIdentity
self.targetView!.center = self.baseOrigin!
self.targetView!.setNeedsLayout()
self.targetView!.layoutIfNeeded()
})
{ [] (finished: Bool) in
self.targetView!.setNeedsLayout()
self.targetView!.layoutIfNeeded()
self.baseOrigin = nil
}
bgView?.removeFromSuperview()
bttnClose?.removeFromSuperview()
}
}
mutating func shrinkAction(sender: UIButton!) {
animation()
}
}
| apache-2.0 | b8a01cccf2b2a04fcae979acfde5d718 | 31.125 | 119 | 0.517156 | 4.680464 | false | false | false | false |
JeffESchmitz/OnTheMap | OnTheMap/OnTheMap/UdacityClient.swift | 1 | 6169 | //
// UdacityClient.swift
// OnTheMap
//
// Created by Jeff Schmitz on 4/30/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import Foundation
// Extends the Client class with specific functionality and data related to the Udacity API
extension Client {
func udacityLogin(username: String, password: String, completionHandler: (result: AnyObject!, error: String?) -> Void) {
let url = Constants.UdacityAPI.BaseUrl + Constants.UdacityAPI.URLPathSeparator + Constants.UdacityAPI.Session
print("url: \(url)")
let jsonBody: [String : AnyObject] = ["udacity" : ["username" : username, "password" : password]]
print("jsonBody: \(jsonBody)")
let tuples = [
(Constants.HttpRequest.AcceptHeaderField, Constants.HttpRequest.ContentJSON),
(Constants.HttpRequest.ContentTypeHeaderField, Constants.HttpRequest.ContentJSON)
]
taskForPOSTMethod(url, jsonBody: jsonBody, requestHeaders: tuples) { (result, error) in
//TODO: JES - 5.1.2016 - refactor below out to common method for FaceBook login to use also
self.processRequestResult(result, error: error, completionHandler: completionHandler)
}
}
func getUdacityUserData(completionHandler: (result: AnyObject!, error: String?) -> Void) {
let urlString = Constants.UdacityAPI.BaseUrl
+ Constants.UdacityAPI.URLPathSeparator
+ Constants.UdacityAPI.Users
+ Constants.UdacityAPI.URLPathSeparator
+ userLogin.accountKey!
print("urlString: \(urlString)")
taskForGETMethod(urlString) { (result, error) in
if let error = error {
print("error: \(error)")
completionHandler(result: false, error: error.valueForKeyPath("userInfo.NSLocalizedDescription") as? String)
} else {
guard let user = result[Constants.UdacityAPI.User] as? [String:AnyObject] else {
completionHandler(result: false, error: "Udacity user infor not found!")
return
}
self.userLogin.userFirstName = user[Constants.UdacityAPI.FirstName] as? String
self.userLogin.userLastName = user[Constants.UdacityAPI.LastName] as? String
completionHandler(result: true, error: "")
}
}
}
func logout(completionHandler: (result: AnyObject!, error: String?) -> Void) {
if userLogin.loginType == .Udacity {
let urlString = Constants.UdacityAPI.BaseUrl
+ Constants.UdacityAPI.URLPathSeparator
+ Constants.UdacityAPI.Session
print("urlString: \(urlString)")
taskForDELETEMethod(urlString, completionHandler: { (result, error) in
if error != nil {
completionHandler(result: false, error: error?.valueForKeyPath("userInfo.NSLocalizedDescription") as? String)
}
else {
guard let _ = result[Constants.UdacityAPI.Session] as? [String:AnyObject] else {
completionHandler(result: false, error: "Logout Failed!")
return
}
completionHandler(result: true, error: nil)
}
})
} else {
facebookManager?.logOut()
completionHandler(result: true, error: nil)
}
}
func facebookLogin(accessToken: String!, completionHandler: (result: AnyObject!, error: String?) -> Void) {
let urlString = Constants.UdacityAPI.BaseUrl + Constants.UdacityAPI.URLPathSeparator + Constants.UdacityAPI.Session
print("urlString: \(urlString)")
let jsonBody: [String : AnyObject] = ["facebook_mobile" : ["access_token" : accessToken]]
print("jsonBody: \(jsonBody)")
let requestHeaders = [
(Constants.HttpRequest.AcceptHeaderField, Constants.HttpRequest.ContentJSON),
(Constants.HttpRequest.ContentTypeHeaderField, Constants.HttpRequest.ContentJSON)
]
taskForPOSTMethod(urlString, jsonBody: jsonBody, requestHeaders: requestHeaders) {
(result, error) in
self.processRequestResult(result, error: error, completionHandler: completionHandler)
}
}
func processRequestResult(result: AnyObject!, error: NSError?, completionHandler: (result: AnyObject!, error: String?) -> Void) {
if let error = error {
completionHandler(result: false, error: error.localizedDescription)
}
else {
guard let account = result[Constants.UdacityAPI.Account] as? [String:AnyObject] else {
completionHandler(result: false,
error: "Login Failed. Unable to find \(Constants.UdacityAPI.Account) in json body.")
return
}
guard let registered = account[Constants.UdacityAPI.Registered] as? Bool where registered else {
completionHandler(result: false,
error: "Login Failed. Unable to find \(Constants.UdacityAPI.Registered) in json body.")
return
}
// store account key for later
self.userLogin.accountKey = account[Constants.UdacityAPI.Key] as? String
guard let session = result[Constants.UdacityAPI.Session] as? [String:AnyObject] else {
completionHandler(result: false, error: "Login Failed. Unable to find \(Constants.UdacityAPI.Session) in json body.")
return
}
// store session id for later
self.userLogin.sessionId = session[Constants.UdacityAPI.Id] as? String
self.getUdacityUserData(completionHandler)
}
}
}
| mit | 973424e8fd12f0b5cb6d75997fed92bb | 38.037975 | 133 | 0.58382 | 5.382199 | false | false | false | false |
nguyenantinhbk77/practice-swift | BackgroundProcessing/StateLab/StateLab/ViewController.swift | 2 | 5481 | //
// ViewController.swift
// StateLab
//
// Created by Domenico on 30/04/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var label:UILabel!
private var smiley:UIImage!
private var smileyView:UIImageView!
private var segmentedControl:UISegmentedControl!
private var index = 0
private var animate:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
index = NSUserDefaults.standardUserDefaults().integerForKey("index")
segmentedControl.selectedSegmentIndex = index;
let bounds = view.bounds
let labelFrame:CGRect = CGRectMake(bounds.origin.x,
CGRectGetMidY(bounds) - 50, bounds.size.width, 100)
label = UILabel(frame:labelFrame)
label.font = UIFont(name:"Helvetica", size:70)
label.text = "Bazinga!"
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.clearColor()
// smiley.png is 84 x 84
let smileyFrame = CGRectMake(CGRectGetMidX(bounds) - 42,
CGRectGetMidY(bounds)/2 - 42, 84, 84)
smileyView = UIImageView(frame:smileyFrame)
smileyView.contentMode = UIViewContentMode.Center
let smileyPath =
NSBundle.mainBundle().pathForResource("smiley", ofType: "png")!
smiley = UIImage(contentsOfFile: smileyPath)
smileyView.image = smiley
UISegmentedControl(items: ["One","Two", "Three", "Four"])
segmentedControl.frame = CGRectMake(bounds.origin.x + 20, 50,
bounds.size.width - 40, 30)
segmentedControl.addTarget(self, action: "selectionChanged:",
forControlEvents: UIControlEvents.ValueChanged)
view.addSubview(segmentedControl)
view.addSubview(smileyView)
view.addSubview(label)
// Notification
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "applicationWillResignActive",
name: UIApplicationWillResignActiveNotification, object: nil)
center.addObserver(self, selector: "applicationDidBecomeActive",
name: UIApplicationDidBecomeActiveNotification, object: nil)
center.addObserver(self, selector: "applicationDidEnterBackground",
name: UIApplicationDidEnterBackgroundNotification, object: nil)
center.addObserver(self, selector: "applicationWillEnterForeground",
name: UIApplicationWillEnterForegroundNotification, object: nil)
}
func applicationWillResignActive() {
println("VC: \(__FUNCTION__)")
animate = false
}
func applicationDidBecomeActive() {
println("VC: \(__FUNCTION__)")
animate = true
rotateLabelDown()
}
func applicationDidEnterBackground() {
println("VC: \(__FUNCTION__)")
NSUserDefaults.standardUserDefaults().setInteger(self.index,
forKey:"index")
let app = UIApplication.sharedApplication()
var taskId:UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
let id = app.beginBackgroundTaskWithExpirationHandler(){
println("Background task ran out of time and was terminated.")
app.endBackgroundTask(taskId)
}
taskId = id
if taskId == UIBackgroundTaskInvalid {
println("Failed to start background task!")
return
}
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
println("Starting background task with " +
"\(app.backgroundTimeRemaining) seconds remaining")
self.smiley = nil;
self.smileyView.image = nil;
// simulate a lengthy (25 seconds) procedure
NSThread.sleepForTimeInterval(25)
println("Finishing background task with " +
"\(app.backgroundTimeRemaining) seconds remaining")
app.endBackgroundTask(taskId)
});
}
func applicationWillEnterForeground() {
println("VC: \(__FUNCTION__)")
let smileyPath =
NSBundle.mainBundle().pathForResource("smiley", ofType:"png")!
smiley = UIImage(contentsOfFile: smileyPath)
smileyView.image = smiley
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func rotateLabelDown() {
UIView.animateWithDuration(0.5, animations: {
self.label.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
},
completion: {(bool) -> Void in
self.rotateLabelUp()
})
}
func rotateLabelUp() {
UIView.animateWithDuration(0.5, animations: {
self.label.transform = CGAffineTransformMakeRotation(0)
},
completion: {(bool) -> Void in
if self.animate{
self.rotateLabelDown()
}
})
}
func selectionChanged(sender:UISegmentedControl) {
index = segmentedControl.selectedSegmentIndex;
}
}
| mit | 22c790e288a18c8385cc6bb6a11ceb59 | 34.134615 | 80 | 0.611202 | 5.564467 | false | false | false | false |
mlgoogle/wp | wp/Model/UserParam.swift | 1 | 1110 | //
// UserParam.swift
// wp
//
// Created by mu on 2017/4/12.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class UserParam: BaseModel {
}
class RegisterParam: BaseModel{
var phone = ""
var pwd = ""
var vCode = ""
var memberId = 0
var agentId = ""
var recommend = ""
var timeStamp = 0
var vToken = ""
var deviceId = UserModel.share().uuid
}
class BingPhoneParam: RegisterParam {
var openid = ""
var nickname = ""
var headerUrl = ""
}
class LoginParam: BaseModel {
var phone = ""
var pwd = ""
var source = 1
var deviceId = UserModel.share().uuid
}
class WechatLoginParam: BaseModel {
var openId = ""
var source = 1
var deviceId = UserModel.share().uuid
}
class ChecktokenParam: BaseModel{
var token = ""
var id = 0
var source = 1
}
class CheckPhoneParam: BaseParam{
var type = 0
var phone = ""
}
class ResetPwdParam: BaseParam{
var phone = UserModel.share().phone!
var pwd = ""
var vCode = ""
var type = 0
var timestamp = 0
var vToken = ""
}
| apache-2.0 | 082d7d0f64f19a6fc13743c3a3a0141f | 14.814286 | 55 | 0.596206 | 3.536741 | false | false | false | false |
Egibide-DAM/swift | 02_ejemplos/06_tipos_personalizados/04_metodos/01_metodos_instancia.playground/Contents.swift | 1 | 413 | class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.increment(by: 5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0
| apache-2.0 | b3816f5f500c638f548b3c713d41e0b9 | 16.208333 | 36 | 0.59322 | 3.654867 | false | false | false | false |
riteshhgupta/TagCellLayout | Source/TagCellLayout.swift | 1 | 6952 | //
// TagCellLayout.swift
// TagCellLayout
//
// Created by Ritesh-Gupta on 20/11/15.
// Copyright © 2015 Ritesh. All rights reserved.
//
import Foundation
import UIKit
public class TagCellLayout: UICollectionViewLayout {
let alignment: LayoutAlignment
var layoutInfoList: [LayoutInfo] = []
var numberOfTagsInCurrentRow = 0
var currentTagIndex: Int = 0
weak var delegate: TagCellLayoutDelegate?
//MARK: - Init Methods
public init(alignment: LayoutAlignment = .left, delegate: TagCellLayoutDelegate?) {
self.delegate = delegate
self.alignment = alignment
super.init()
}
required public init?(coder aDecoder: NSCoder) {
alignment = .left
super.init(coder: aDecoder)
}
override convenience init() {
self.init(delegate: nil)
}
//MARK: - Override Methods
override public func prepare() {
resetLayoutState()
setupTagCellLayout()
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard layoutInfoList.count > indexPath.row else { return nil }
return layoutInfoList[indexPath.row].layoutAttribute
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard !layoutInfoList.isEmpty else { return nil }
return layoutInfoList
.lazy
.map { $0.layoutAttribute }
.filter { rect.intersects($0.frame) }
}
override public var collectionViewContentSize: CGSize {
let width = collectionViewWidth
let height = layoutInfoList
.filter { $0.isFirstElementInARow }
.reduce(0, { $0 + $1.layoutAttribute.frame.height })
return CGSize(width: width, height: height)
}
}
//MARK: - Private Methods
private extension TagCellLayout {
var currentTagFrame: CGRect {
guard let info = currentTagLayoutInfo?.layoutAttribute else { return .zero }
var frame = info.frame
frame.origin.x += info.bounds.width
return frame
}
var currentTagLayoutInfo: LayoutInfo? {
let index = max(0, currentTagIndex - 1)
guard layoutInfoList.count > index else { return nil }
return layoutInfoList[index]
}
var tagsCount: Int {
return collectionView?.numberOfItems(inSection: 0) ?? 0
}
var collectionViewWidth: CGFloat {
return collectionView?.frame.size.width ?? 0
}
var isLastRow: Bool {
return currentTagIndex == (tagsCount - 1)
}
func setupTagCellLayout() {
// delegate and collectionview shouldn't be nil
guard delegate != nil, collectionView != nil else {
// otherwise throwing an error
handleErrorState()
return
}
// basic layout setup which is independent of TagAlignment type
basicLayoutSetup()
// handle if TagAlignment is other than Left
handleTagAlignment()
}
func basicLayoutSetup() {
// asking the client for a fixed tag height
// iterating over every tag and constructing its layout attribute
(0 ..< tagsCount).forEach {
currentTagIndex = $0
// creating layout and adding it to the dataSource
createLayoutAttributes()
// configuring white space info || this is later used for .Right or .Center alignment
configureWhiteSpace()
// processing info for next tag || setting up the coordinates for next tag
configurePositionForNextTag()
// handling tha layout for last row separately
handleWhiteSpaceForLastRow()
}
}
func createLayoutAttributes() {
// calculating tag-size
let tagSize = delegate!.tagCellLayoutTagSize(layout: self, atIndex: currentTagIndex)
let layoutInfo = tagCellLayoutInfo(tagIndex: currentTagIndex, tagSize: tagSize)
layoutInfoList.append(layoutInfo)
}
func tagCellLayoutInfo(tagIndex: Int, tagSize: CGSize) -> LayoutInfo {
// local data-structure (TagCellLayoutInfo) that has been used in this library to store attribute and white-space info
var isFirstElementInARow = tagIndex == 0
var tagFrame = currentTagFrame
tagFrame.size = tagSize
// if next tag goes out of screen then move it to next row
if shouldMoveTagToNextRow(tagWidth: tagSize.width) {
tagFrame.origin.x = 0.0
tagFrame.origin.y += currentTagFrame.height
isFirstElementInARow = true
}
let attribute = layoutAttribute(tagIndex: tagIndex, tagFrame: tagFrame)
var info = LayoutInfo(layoutAttribute: attribute)
info.isFirstElementInARow = isFirstElementInARow
return info
}
func shouldMoveTagToNextRow(tagWidth: CGFloat) -> Bool {
return ((currentTagFrame.origin.x + tagWidth) > collectionViewWidth)
}
func layoutAttribute(tagIndex: Int, tagFrame: CGRect) -> UICollectionViewLayoutAttributes {
let indexPath = IndexPath(item: tagIndex, section: 0)
let layoutAttribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
layoutAttribute.frame = tagFrame
return layoutAttribute
}
func configureWhiteSpace() {
let layoutInfo = layoutInfoList[currentTagIndex].layoutAttribute
let tagWidth = layoutInfo.frame.size.width
if shouldMoveTagToNextRow(tagWidth: tagWidth) {
applyWhiteSpace(startingIndex: (currentTagIndex - 1))
}
}
func applyWhiteSpace(startingIndex: Int) {
let lastIndex = startingIndex - numberOfTagsInCurrentRow
let whiteSpace = calculateWhiteSpace(tagIndex: startingIndex)
for tagIndex in (lastIndex+1) ..< (startingIndex+1) {
insertWhiteSpace(tagIndex: tagIndex, whiteSpace: whiteSpace)
}
}
func calculateWhiteSpace(tagIndex: Int) -> CGFloat {
let tagFrame = tagFrameForIndex(tagIndex: tagIndex)
let whiteSpace = collectionViewWidth - (tagFrame.origin.x + tagFrame.size.width)
return whiteSpace
}
func insertWhiteSpace(tagIndex: Int, whiteSpace: CGFloat) {
var info = layoutInfoList[tagIndex]
let factor = alignment.distributionDivisionFactor
info.whiteSpace = whiteSpace/factor
layoutInfoList[tagIndex] = info
}
func tagFrameForIndex(tagIndex: Int) -> CGRect {
let tagFrame = tagIndex > -1 ? layoutInfoList[tagIndex].layoutAttribute.frame : .zero
return tagFrame
}
func configurePositionForNextTag() {
let layoutInfo = layoutInfoList[currentTagIndex].layoutAttribute
let moveTag = shouldMoveTagToNextRow(tagWidth: layoutInfo.frame.size.width)
numberOfTagsInCurrentRow = moveTag ? 1 : (numberOfTagsInCurrentRow + 1)
}
func handleTagAlignment() {
guard alignment != .left else { return }
let tagsCount = collectionView!.numberOfItems(inSection: 0)
for tagIndex in 0 ..< tagsCount {
var tagFrame = layoutInfoList[tagIndex].layoutAttribute.frame
let whiteSpace = layoutInfoList[tagIndex].whiteSpace
tagFrame.origin.x += whiteSpace
let tagAttribute = layoutAttribute(tagIndex: tagIndex, tagFrame: tagFrame)
layoutInfoList[tagIndex].layoutAttribute = tagAttribute
}
}
func handleWhiteSpaceForLastRow() {
guard isLastRow else { return }
applyWhiteSpace(startingIndex: (tagsCount-1))
}
func handleErrorState() {
print("TagCollectionViewCellLayout is not properly configured")
}
func resetLayoutState() {
layoutInfoList = Array<LayoutInfo>()
numberOfTagsInCurrentRow = 0
}
}
| mit | 80973eadaba0e333e409825c42774fa3 | 28.578723 | 120 | 0.744929 | 3.905056 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Tests/SwiftProtobufTests/Test_TextFormat_proto3.swift | 1 | 60599 | // Tests/SwiftProtobufTests/Test_TextFormat_proto3.swift - Exercise proto3 text format coding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This is a set of tests for text format protobuf files.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_TextFormat_proto3: XCTestCase, PBTestHelpers {
typealias MessageTestType = Proto3TestAllTypes
func testDecoding_comments() {
assertTextFormatDecodeSucceeds("single_int32: 41#single_int32: 42\nsingle_int64: 8") {
(o: MessageTestType) in
return o.singleInt32 == 41 && o.singleInt64 == 8
}
}
//
// Singular types
//
func testEncoding_singleInt32() {
var a = MessageTestType()
a.singleInt32 = 41
XCTAssertEqual("single_int32: 41\n", a.textFormatString())
assertTextFormatEncode("single_int32: 1\n") {(o: inout MessageTestType) in o.singleInt32 = 1 }
assertTextFormatEncode("single_int32: 12\n") {(o: inout MessageTestType) in o.singleInt32 = 12 }
assertTextFormatEncode("single_int32: 123\n") {(o: inout MessageTestType) in o.singleInt32 = 123 }
assertTextFormatEncode("single_int32: 1234\n") {(o: inout MessageTestType) in o.singleInt32 = 1234 }
assertTextFormatEncode("single_int32: 12345\n") {(o: inout MessageTestType) in o.singleInt32 = 12345 }
assertTextFormatEncode("single_int32: 123456\n") {(o: inout MessageTestType) in o.singleInt32 = 123456 }
assertTextFormatEncode("single_int32: 1234567\n") {(o: inout MessageTestType) in o.singleInt32 = 1234567 }
assertTextFormatEncode("single_int32: 12345678\n") {(o: inout MessageTestType) in o.singleInt32 = 12345678 }
assertTextFormatEncode("single_int32: 123456789\n") {(o: inout MessageTestType) in o.singleInt32 = 123456789 }
assertTextFormatEncode("single_int32: 1234567890\n") {(o: inout MessageTestType) in o.singleInt32 = 1234567890 }
assertTextFormatEncode("single_int32: 1\n") {(o: inout MessageTestType) in o.singleInt32 = 1 }
assertTextFormatEncode("single_int32: 10\n") {(o: inout MessageTestType) in o.singleInt32 = 10 }
assertTextFormatEncode("single_int32: 100\n") {(o: inout MessageTestType) in o.singleInt32 = 100 }
assertTextFormatEncode("single_int32: 1000\n") {(o: inout MessageTestType) in o.singleInt32 = 1000 }
assertTextFormatEncode("single_int32: 10000\n") {(o: inout MessageTestType) in o.singleInt32 = 10000 }
assertTextFormatEncode("single_int32: 100000\n") {(o: inout MessageTestType) in o.singleInt32 = 100000 }
assertTextFormatEncode("single_int32: 1000000\n") {(o: inout MessageTestType) in o.singleInt32 = 1000000 }
assertTextFormatEncode("single_int32: 10000000\n") {(o: inout MessageTestType) in o.singleInt32 = 10000000 }
assertTextFormatEncode("single_int32: 100000000\n") {(o: inout MessageTestType) in o.singleInt32 = 100000000 }
assertTextFormatEncode("single_int32: 1000000000\n") {(o: inout MessageTestType) in o.singleInt32 = 1000000000 }
assertTextFormatEncode("single_int32: 41\n") {(o: inout MessageTestType) in
o.singleInt32 = 41 }
assertTextFormatEncode("single_int32: 1\n") {(o: inout MessageTestType) in
o.singleInt32 = 1
}
assertTextFormatEncode("single_int32: -1\n") {(o: inout MessageTestType) in
o.singleInt32 = -1
}
assertTextFormatDecodeSucceeds("single_int32:0x1234") {(o: MessageTestType) in
return o.singleInt32 == 0x1234
}
assertTextFormatDecodeSucceeds("single_int32:41") {(o: MessageTestType) in
return o.singleInt32 == 41
}
assertTextFormatDecodeSucceeds("single_int32: 41#single_int32: 42") {
(o: MessageTestType) in
return o.singleInt32 == 41
}
assertTextFormatDecodeSucceeds("single_int32: 41 single_int32: 42") {
(o: MessageTestType) in
return o.singleInt32 == 42
}
assertTextFormatDecodeFails("single_int32: a\n")
assertTextFormatDecodeFails("single_int32: 999999999999999999999999999999999999\n")
assertTextFormatDecodeFails("single_int32: 1,2\n")
assertTextFormatDecodeFails("single_int32: 1.2\n")
assertTextFormatDecodeFails("single_int32: { }\n")
assertTextFormatDecodeFails("single_int32: \"hello\"\n")
assertTextFormatDecodeFails("single_int32: true\n")
assertTextFormatDecodeFails("single_int32: 0x80000000\n")
assertTextFormatDecodeSucceeds("single_int32: -0x80000000\n") {(o: MessageTestType) in
return o.singleInt32 == -0x80000000
}
assertTextFormatDecodeFails("single_int32: -0x80000001\n")
}
func testEncoding_singleInt64() {
var a = MessageTestType()
a.singleInt64 = 2
XCTAssertEqual("single_int64: 2\n", a.textFormatString())
assertTextFormatEncode("single_int64: 1\n") {(o: inout MessageTestType) in o.singleInt64 = 1 }
assertTextFormatEncode("single_int64: 12\n") {(o: inout MessageTestType) in o.singleInt64 = 12 }
assertTextFormatEncode("single_int64: 123\n") {(o: inout MessageTestType) in o.singleInt64 = 123 }
assertTextFormatEncode("single_int64: 1234\n") {(o: inout MessageTestType) in o.singleInt64 = 1234 }
assertTextFormatEncode("single_int64: 12345\n") {(o: inout MessageTestType) in o.singleInt64 = 12345 }
assertTextFormatEncode("single_int64: 123456\n") {(o: inout MessageTestType) in o.singleInt64 = 123456 }
assertTextFormatEncode("single_int64: 1234567\n") {(o: inout MessageTestType) in o.singleInt64 = 1234567 }
assertTextFormatEncode("single_int64: 12345678\n") {(o: inout MessageTestType) in o.singleInt64 = 12345678 }
assertTextFormatEncode("single_int64: 123456789\n") {(o: inout MessageTestType) in o.singleInt64 = 123456789 }
assertTextFormatEncode("single_int64: 1234567890\n") {(o: inout MessageTestType) in o.singleInt64 = 1234567890 }
assertTextFormatEncode("single_int64: 1\n") {(o: inout MessageTestType) in o.singleInt64 = 1 }
assertTextFormatEncode("single_int64: 10\n") {(o: inout MessageTestType) in o.singleInt64 = 10 }
assertTextFormatEncode("single_int64: 100\n") {(o: inout MessageTestType) in o.singleInt64 = 100 }
assertTextFormatEncode("single_int64: 1000\n") {(o: inout MessageTestType) in o.singleInt64 = 1000 }
assertTextFormatEncode("single_int64: 10000\n") {(o: inout MessageTestType) in o.singleInt64 = 10000 }
assertTextFormatEncode("single_int64: 100000\n") {(o: inout MessageTestType) in o.singleInt64 = 100000 }
assertTextFormatEncode("single_int64: 1000000\n") {(o: inout MessageTestType) in o.singleInt64 = 1000000 }
assertTextFormatEncode("single_int64: 10000000\n") {(o: inout MessageTestType) in o.singleInt64 = 10000000 }
assertTextFormatEncode("single_int64: 100000000\n") {(o: inout MessageTestType) in o.singleInt64 = 100000000 }
assertTextFormatEncode("single_int64: 1000000000\n") {(o: inout MessageTestType) in o.singleInt64 = 1000000000 }
assertTextFormatEncode("single_int64: -2\n") {(o: inout MessageTestType) in o.singleInt64 = -2 }
assertTextFormatDecodeSucceeds("single_int64: 0x1234567812345678\n") {(o: MessageTestType) in
return o.singleInt64 == 0x1234567812345678
}
assertTextFormatDecodeFails("single_int64: a\n")
assertTextFormatDecodeFails("single_int64: 999999999999999999999999999999999999\n")
assertTextFormatDecodeFails("single_int64: 1,2\n")
}
func testEncoding_singleUint32() {
var a = MessageTestType()
a.singleUint32 = 3
XCTAssertEqual("single_uint32: 3\n", a.textFormatString())
assertTextFormatEncode("single_uint32: 3\n") {(o: inout MessageTestType) in
o.singleUint32 = 3
}
assertTextFormatDecodeSucceeds("single_uint32: 3u") {
(o: MessageTestType) in
return o.singleUint32 == 3
}
assertTextFormatDecodeSucceeds("single_uint32: 3u single_int32: 1") {
(o: MessageTestType) in
return o.singleUint32 == 3 && o.singleInt32 == 1
}
assertTextFormatDecodeFails("single_uint32: -3\n")
assertTextFormatDecodeFails("single_uint32: 3x\n")
assertTextFormatDecodeFails("single_uint32: 3,4\n")
assertTextFormatDecodeFails("single_uint32: 999999999999999999999999999999999999\n")
assertTextFormatDecodeFails("single_uint32 3\n")
assertTextFormatDecodeFails("3u")
assertTextFormatDecodeFails("single_uint32: a\n")
assertTextFormatDecodeFails("single_uint32 single_uint32: 7\n")
}
func testEncoding_singleUint64() {
var a = MessageTestType()
a.singleUint64 = 4
XCTAssertEqual("single_uint64: 4\n", a.textFormatString())
assertTextFormatEncode("single_uint64: 4\n") {(o: inout MessageTestType) in
o.singleUint64 = 4
}
assertTextFormatDecodeSucceeds("single_uint64: 0xf234567812345678\n") {(o: MessageTestType) in
return o.singleUint64 == 0xf234567812345678
}
assertTextFormatDecodeFails("single_uint64: a\n")
assertTextFormatDecodeFails("single_uint64: 999999999999999999999999999999999999\n")
assertTextFormatDecodeFails("single_uint64: 7,8")
assertTextFormatDecodeFails("single_uint64: [7]")
}
func testEncoding_singleSint32() {
var a = MessageTestType()
a.singleSint32 = 5
XCTAssertEqual("single_sint32: 5\n", a.textFormatString())
assertTextFormatEncode("single_sint32: 5\n") {(o: inout MessageTestType) in
o.singleSint32 = 5
}
assertTextFormatEncode("single_sint32: -5\n") {(o: inout MessageTestType) in
o.singleSint32 = -5
}
assertTextFormatDecodeSucceeds(" single_sint32:-5 ") {
(o: MessageTestType) in
return o.singleSint32 == -5
}
assertTextFormatDecodeFails("single_sint32: a\n")
}
func testEncoding_singleSint64() {
var a = MessageTestType()
a.singleSint64 = 6
XCTAssertEqual("single_sint64: 6\n", a.textFormatString())
assertTextFormatEncode("single_sint64: 6\n") {(o: inout MessageTestType) in
o.singleSint64 = 6
}
assertTextFormatDecodeFails("single_sint64: a\n")
}
func testEncoding_singleFixed32() {
var a = MessageTestType()
a.singleFixed32 = 7
XCTAssertEqual("single_fixed32: 7\n", a.textFormatString())
assertTextFormatEncode("single_fixed32: 7\n") {(o: inout MessageTestType) in
o.singleFixed32 = 7
}
assertTextFormatDecodeFails("single_fixed32: a\n")
}
func testEncoding_singleFixed64() {
var a = MessageTestType()
a.singleFixed64 = 8
XCTAssertEqual("single_fixed64: 8\n", a.textFormatString())
assertTextFormatEncode("single_fixed64: 8\n") {(o: inout MessageTestType) in
o.singleFixed64 = 8
}
assertTextFormatDecodeFails("single_fixed64: a\n")
}
func testEncoding_singleSfixed32() {
var a = MessageTestType()
a.singleSfixed32 = 9
XCTAssertEqual("single_sfixed32: 9\n", a.textFormatString())
assertTextFormatEncode("single_sfixed32: 9\n") {(o: inout MessageTestType) in
o.singleSfixed32 = 9
}
assertTextFormatDecodeFails("single_sfixed32: a\n")
}
func testEncoding_singleSfixed64() {
var a = MessageTestType()
a.singleSfixed64 = 10
XCTAssertEqual("single_sfixed64: 10\n", a.textFormatString())
assertTextFormatEncode("single_sfixed64: 10\n") {(o: inout MessageTestType) in
o.singleSfixed64 = 10
}
assertTextFormatDecodeFails("single_sfixed64: a\n")
}
private func assertRoundTripText(file: XCTestFileArgType = #file, line: UInt = #line, configure: (inout MessageTestType) -> Void) {
var original = MessageTestType()
configure(&original)
let text = original.textFormatString()
do {
let decoded = try MessageTestType(textFormatString: text)
XCTAssertEqual(original, decoded)
} catch let e {
XCTFail("Failed to decode \(e): \(text)", file: file, line: line)
}
}
func testEncoding_singleFloat() {
var a = MessageTestType()
a.singleFloat = 11
XCTAssertEqual("single_float: 11\n", a.textFormatString())
assertTextFormatEncode("single_float: 11\n") {(o: inout MessageTestType) in
o.singleFloat = 11
}
assertTextFormatDecodeSucceeds("single_float: 1.0f") {
(o: MessageTestType) in
return o.singleFloat == 1.0
}
assertTextFormatDecodeSucceeds("single_float: 1.5e3") {
(o: MessageTestType) in
return o.singleFloat == 1.5e3
}
assertTextFormatDecodeSucceeds("single_float: -4.75") {
(o: MessageTestType) in
return o.singleFloat == -4.75
}
assertTextFormatDecodeSucceeds("single_float: 1.0f single_int32: 1") {
(o: MessageTestType) in
return o.singleFloat == 1.0 && o.singleInt32 == 1
}
assertTextFormatDecodeSucceeds("single_float: 1.0 single_int32: 1") {
(o: MessageTestType) in
return o.singleFloat == 1.0 && o.singleInt32 == 1
}
assertTextFormatDecodeSucceeds("single_float: 1.0f\n") {
(o: MessageTestType) in
return o.singleFloat == 1.0
}
assertTextFormatEncode("single_float: inf\n") {(o: inout MessageTestType) in o.singleFloat = Float.infinity}
assertTextFormatEncode("single_float: -inf\n") {(o: inout MessageTestType) in o.singleFloat = -Float.infinity}
let b = Proto3TestAllTypes.with {$0.singleFloat = Float.nan}
XCTAssertEqual("single_float: nan\n", b.textFormatString())
do {
let nan1 = try Proto3TestAllTypes(textFormatString: "single_float: nan\n")
XCTAssert(nan1.singleFloat.isNaN)
} catch let e {
XCTFail("Decoding nan failed: \(e)")
}
do {
let nan2 = try Proto3TestAllTypes(textFormatString: "single_float: NaN\n")
XCTAssert(nan2.singleFloat.isNaN)
} catch let e {
XCTFail("Decoding nan failed: \(e)")
}
assertTextFormatDecodeFails("single_float: nansingle_int32: 1\n")
assertTextFormatDecodeSucceeds("single_float: INFINITY\n") {(o: MessageTestType) in
return o.singleFloat == Float.infinity
}
assertTextFormatDecodeSucceeds("single_float: Infinity\n") {(o: MessageTestType) in
return o.singleFloat == Float.infinity
}
assertTextFormatDecodeSucceeds("single_float: -INFINITY\n") {(o: MessageTestType) in
return o.singleFloat == -Float.infinity
}
assertTextFormatDecodeSucceeds("single_float: -Infinity\n") {(o: MessageTestType) in
return o.singleFloat == -Float.infinity
}
assertTextFormatDecodeFails("single_float: INFINITY_AND_BEYOND\n")
assertTextFormatDecodeFails("single_float: infinitysingle_int32: 1\n")
assertTextFormatDecodeFails("single_float: a\n")
assertTextFormatDecodeFails("single_float: 1,2\n")
assertTextFormatDecodeFails("single_float: 0xf\n")
assertTextFormatDecodeFails("single_float: 012\n")
// A wide range of numbers should exactly round-trip
assertRoundTripText {$0.singleFloat = 0.1}
assertRoundTripText {$0.singleFloat = 0.01}
assertRoundTripText {$0.singleFloat = 0.001}
assertRoundTripText {$0.singleFloat = 0.0001}
assertRoundTripText {$0.singleFloat = 0.00001}
assertRoundTripText {$0.singleFloat = 0.000001}
assertRoundTripText {$0.singleFloat = 1e-10}
assertRoundTripText {$0.singleFloat = 1e-20}
assertRoundTripText {$0.singleFloat = 1e-30}
assertRoundTripText {$0.singleFloat = 1e-40}
assertRoundTripText {$0.singleFloat = 1e-50}
assertRoundTripText {$0.singleFloat = 1e-60}
assertRoundTripText {$0.singleFloat = 1e-100}
assertRoundTripText {$0.singleFloat = 1e-200}
assertRoundTripText {$0.singleFloat = Float.pi}
assertRoundTripText {$0.singleFloat = 123456.789123456789123}
assertRoundTripText {$0.singleFloat = 1999.9999999999}
assertRoundTripText {$0.singleFloat = 1999.9}
assertRoundTripText {$0.singleFloat = 1999.99}
assertRoundTripText {$0.singleFloat = 1999.99}
assertRoundTripText {$0.singleFloat = 3.402823567e+38}
assertRoundTripText {$0.singleFloat = 1.1754944e-38}
}
func testEncoding_singleDouble() {
var a = MessageTestType()
a.singleDouble = 12
XCTAssertEqual("single_double: 12\n", a.textFormatString())
assertTextFormatEncode("single_double: 12\n") {(o: inout MessageTestType) in o.singleDouble = 12 }
assertTextFormatEncode("single_double: inf\n") {(o: inout MessageTestType) in o.singleDouble = Double.infinity}
assertTextFormatEncode("single_double: -inf\n") {(o: inout MessageTestType) in o.singleDouble = -Double.infinity}
let b = Proto3TestAllTypes.with {$0.singleDouble = Double.nan}
XCTAssertEqual("single_double: nan\n", b.textFormatString())
assertTextFormatDecodeSucceeds("single_double: INFINITY\n") {(o: MessageTestType) in
return o.singleDouble == Double.infinity
}
assertTextFormatDecodeSucceeds("single_double: Infinity\n") {(o: MessageTestType) in
return o.singleDouble == Double.infinity
}
assertTextFormatDecodeSucceeds("single_double: -INFINITY\n") {(o: MessageTestType) in
return o.singleDouble == -Double.infinity
}
assertTextFormatDecodeSucceeds("single_double: -Infinity\n") {(o: MessageTestType) in
return o.singleDouble == -Double.infinity
}
assertTextFormatDecodeFails("single_double: INFINITY_AND_BEYOND\n")
assertTextFormatDecodeFails("single_double: INFIN\n")
assertTextFormatDecodeFails("single_double: a\n")
assertTextFormatDecodeFails("single_double: 1.2.3\n")
assertTextFormatDecodeFails("single_double: 0xf\n")
assertTextFormatDecodeFails("single_double: 0123\n")
// A wide range of numbers should exactly round-trip
assertRoundTripText {$0.singleDouble = 0.1}
assertRoundTripText {$0.singleDouble = 0.01}
assertRoundTripText {$0.singleDouble = 0.001}
assertRoundTripText {$0.singleDouble = 0.0001}
assertRoundTripText {$0.singleDouble = 0.00001}
assertRoundTripText {$0.singleDouble = 0.000001}
assertRoundTripText {$0.singleDouble = 1e-10}
assertRoundTripText {$0.singleDouble = 1e-20}
assertRoundTripText {$0.singleDouble = 1e-30}
assertRoundTripText {$0.singleDouble = 1e-40}
assertRoundTripText {$0.singleDouble = 1e-50}
assertRoundTripText {$0.singleDouble = 1e-60}
assertRoundTripText {$0.singleDouble = 1e-100}
assertRoundTripText {$0.singleDouble = 1e-200}
assertRoundTripText {$0.singleDouble = Double.pi}
assertRoundTripText {$0.singleDouble = 123456.789123456789123}
assertRoundTripText {$0.singleDouble = 1.7976931348623157e+308}
assertRoundTripText {$0.singleDouble = 2.22507385850720138309e-308}
}
func testEncoding_singleBool() {
var a = MessageTestType()
a.singleBool = true
XCTAssertEqual("single_bool: true\n", a.textFormatString())
a.singleBool = false
XCTAssertEqual("", a.textFormatString())
assertTextFormatEncode("single_bool: true\n") {(o: inout MessageTestType) in
o.singleBool = true
}
assertTextFormatDecodeSucceeds("single_bool:true") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:true ") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:true\n ") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:True\n ") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:t\n ") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:1\n ") {(o: MessageTestType) in
return o.singleBool == true
}
assertTextFormatDecodeSucceeds("single_bool:false\n ") {(o: MessageTestType) in
return o.singleBool == false
}
assertTextFormatDecodeSucceeds("single_bool:False\n ") {(o: MessageTestType) in
return o.singleBool == false
}
assertTextFormatDecodeSucceeds("single_bool:f\n ") {(o: MessageTestType) in
return o.singleBool == false
}
assertTextFormatDecodeSucceeds("single_bool:0\n ") {(o: MessageTestType) in
return o.singleBool == false
}
assertTextFormatDecodeFails("single_bool: 10\n")
assertTextFormatDecodeFails("single_bool: tRue\n")
assertTextFormatDecodeFails("single_bool: tr\n")
assertTextFormatDecodeFails("single_bool: tru\n")
assertTextFormatDecodeFails("single_bool: truE\n")
assertTextFormatDecodeFails("single_bool: TRUE\n")
assertTextFormatDecodeFails("single_bool: faLse\n")
assertTextFormatDecodeFails("single_bool: 2\n")
assertTextFormatDecodeFails("single_bool: -0\n")
assertTextFormatDecodeFails("single_bool: on\n")
assertTextFormatDecodeFails("single_bool: a\n")
}
// TODO: Need to verify the behavior here with extended Unicode text
// and UTF-8 encoded by C++ implementation
func testEncoding_singleString() {
var a = MessageTestType()
a.singleString = "abc"
XCTAssertEqual("single_string: \"abc\"\n", a.textFormatString())
assertTextFormatEncode("single_string: \" !\\\"#$%&'\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{20}\u{21}\u{22}\u{23}\u{24}\u{25}\u{26}\u{27}"
}
assertTextFormatEncode("single_string: \"XYZ[\\\\]^_\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{58}\u{59}\u{5a}\u{5b}\u{5c}\u{5d}\u{5e}\u{5f}"
}
assertTextFormatEncode("single_string: \"xyz{|}~\\177\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{78}\u{79}\u{7a}\u{7b}\u{7c}\u{7d}\u{7e}\u{7f}"
}
assertTextFormatEncode("single_string: \"\u{80}\u{81}\u{82}\u{83}\u{84}\u{85}\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{80}\u{81}\u{82}\u{83}\u{84}\u{85}"
}
assertTextFormatEncode("single_string: \"øùúûüýþÿ\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{f8}\u{f9}\u{fa}\u{fb}\u{fc}\u{fd}\u{fe}\u{ff}"
}
// Adjacent quoted strings concatenate, see
// google/protobuf/text_format_unittest.cc#L597
assertTextFormatDecodeSucceeds("single_string: \"abc\"\"def\"") {
(o: MessageTestType) in
return o.singleString == "abcdef"
}
assertTextFormatDecodeSucceeds("single_string: \"abc\" \"def\"") {
(o: MessageTestType) in
return o.singleString == "abcdef"
}
assertTextFormatDecodeSucceeds("single_string: \"abc\" \"def\"") {
(o: MessageTestType) in
return o.singleString == "abcdef"
}
// Adjacent quoted strings concatenate across multiple lines
assertTextFormatDecodeSucceeds("single_string: \"abc\"\n\"def\"") {
(o: MessageTestType) in
return o.singleString == "abcdef"
}
assertTextFormatDecodeSucceeds("single_string: \"abc\"\n \t \"def\"\n\"ghi\"\n") {
(o: MessageTestType) in
return o.singleString == "abcdefghi"
}
assertTextFormatDecodeSucceeds("single_string: \"abc\"\n\'def\'\n\"ghi\"\n") {
(o: MessageTestType) in
return o.singleString == "abcdefghi"
}
assertTextFormatDecodeSucceeds("single_string: \"abcdefghi\"") {
(o: MessageTestType) in
return o.singleString == "abcdefghi"
}
// Note: Values 0-127 are same whether viewed as Unicode code
// points or UTF-8 bytes.
assertTextFormatDecodeSucceeds("single_string: \"\\a\\b\\f\\n\\r\\t\\v\\\"\\'\\\\\\?\"") {
(o: MessageTestType) in
return o.singleString == "\u{07}\u{08}\u{0C}\u{0A}\u{0D}\u{09}\u{0B}\"'\\?"
}
assertTextFormatDecodeFails("single_string: \"\\z\"")
assertTextFormatDecodeSucceeds("single_string: \"\\001\\01\\1\\0011\\010\\289\"") {
(o: MessageTestType) in
return o.singleString == "\u{01}\u{01}\u{01}\u{01}\u{31}\u{08}\u{02}89"
}
assertTextFormatDecodeSucceeds("single_string: \"\\x1\\x12\\x123\\x1234\"") {
(o: MessageTestType) in
return o.singleString == "\u{01}\u{12}\u{23}\u{34}"
}
assertTextFormatDecodeSucceeds("single_string: \"\\x0f\\x3g\"") {
(o: MessageTestType) in
return o.singleString == "\u{0f}\u{03}g"
}
assertTextFormatEncode("single_string: \"abc\"\n") {(o: inout MessageTestType) in
o.singleString = "abc"
}
assertTextFormatDecodeFails("single_string:hello")
assertTextFormatDecodeFails("single_string: \"hello\'")
assertTextFormatDecodeFails("single_string: \'hello\"")
assertTextFormatDecodeFails("single_string: \"hello")
}
func testEncoding_singleString_controlCharacters() throws {
// This is known to fail on Swift Linux 3.1 and earlier,
// so skip it there.
// See https://bugs.swift.org/browse/SR-4218 for details.
#if !os(Linux) || swift(>=3.2)
assertTextFormatEncode("single_string: \"\\001\\002\\003\\004\\005\\006\\007\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{01}\u{02}\u{03}\u{04}\u{05}\u{06}\u{07}"
}
assertTextFormatEncode("single_string: \"\\b\\t\\n\\v\\f\\r\\016\\017\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{08}\u{09}\u{0a}\u{0b}\u{0c}\u{0d}\u{0e}\u{0f}"
}
assertTextFormatEncode("single_string: \"\\020\\021\\022\\023\\024\\025\\026\\027\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{10}\u{11}\u{12}\u{13}\u{14}\u{15}\u{16}\u{17}"
}
assertTextFormatEncode("single_string: \"\\030\\031\\032\\033\\034\\035\\036\\037\"\n") {
(o: inout MessageTestType) in
o.singleString = "\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f}"
}
#endif
}
func testEncoding_singleString_UTF8() throws {
// We encode to/from a string, not a sequence of bytes, so valid
// Unicode characters just get preserved on both encode and decode:
assertTextFormatEncode("single_string: \"☞\"\n") {(o: inout MessageTestType) in
o.singleString = "☞"
}
// Other encoders write each byte of a UTF-8 sequence, maybe in hex:
assertTextFormatDecodeSucceeds("single_string: \"\\xE2\\x98\\x9E\"") {(o: MessageTestType) in
return o.singleString == "☞"
}
// Or maybe in octal:
assertTextFormatDecodeSucceeds("single_string: \"\\342\\230\\236\"") {(o: MessageTestType) in
return o.singleString == "☞"
}
// Each string piece is decoded separately, broken UTF-8 is an error
assertTextFormatDecodeFails("single_string: \"\\342\\230\" \"\\236\"")
}
func testEncoding_singleBytes() throws {
let o = Proto3TestAllTypes.with { $0.singleBytes = Data() }
XCTAssertEqual("", o.textFormatString())
assertTextFormatEncode("single_bytes: \"AB\"\n") {(o: inout MessageTestType) in
o.singleBytes = Data(bytes: [65, 66])
}
assertTextFormatEncode("single_bytes: \"\\000\\001AB\\177\\200\\377\"\n") {(o: inout MessageTestType) in
o.singleBytes = Data(bytes: [0, 1, 65, 66, 127, 128, 255])
}
assertTextFormatEncode("single_bytes: \"\\b\\t\\n\\v\\f\\r\\\"'?\\\\\"\n") {(o: inout MessageTestType) in
o.singleBytes = Data(bytes: [8, 9, 10, 11, 12, 13, 34, 39, 63, 92])
}
assertTextFormatDecodeSucceeds("single_bytes: \"A\" \"B\"\n") {(o: MessageTestType) in
return o.singleBytes == Data(bytes: [65, 66])
}
assertTextFormatDecodeSucceeds("single_bytes: \"\\0\\1AB\\178\\189\\x61\\xdq\\x123456789\"\n") {(o: MessageTestType) in
return o.singleBytes == Data(bytes: [0, 1, 65, 66, 15, 56, 1, 56, 57, 97, 13, 113, 137])
}
// "\1" followed by "2", not "\12"
assertTextFormatDecodeSucceeds("single_bytes: \"\\1\" \"2\"") {(o: MessageTestType) in
return o.singleBytes == Data(bytes: [1, 50]) // Not [10]
}
// "\x61" followed by "6" and "2", not "\x6162" (== "\x62")
assertTextFormatDecodeSucceeds("single_bytes: \"\\x61\" \"62\"") {(o: MessageTestType) in
return o.singleBytes == Data(bytes: [97, 54, 50]) // Not [98]
}
assertTextFormatDecodeSucceeds("single_bytes: \"\"\n") {(o: MessageTestType) in
return o.singleBytes == Data()
}
assertTextFormatDecodeSucceeds("single_bytes: \"\\b\\t\\n\\v\\f\\r\\\"\\'\\?'\"\n") {(o: MessageTestType) in
return o.singleBytes == Data(bytes: [8, 9, 10, 11, 12, 13, 34, 39, 63, 39])
}
assertTextFormatDecodeFails("single_bytes: 10\n")
assertTextFormatDecodeFails("single_bytes: \"\\\"\n")
assertTextFormatDecodeFails("single_bytes: \"\\x\"\n")
assertTextFormatDecodeFails("single_bytes: \"\\x&\"\n")
assertTextFormatDecodeFails("single_bytes: \"\\xg\"\n")
assertTextFormatDecodeFails("single_bytes: \"\\q\"\n")
}
func testEncoding_singleBytes_roundtrip() throws {
for i in UInt8(0)...UInt8(255) {
let d = Data(bytes: [i])
let message = Proto3TestAllTypes.with { $0.singleBytes = d }
let text = message.textFormatString()
let decoded = try Proto3TestAllTypes(textFormatString: text)
XCTAssertEqual(decoded, message)
XCTAssertEqual(message.singleBytes[0], i)
}
}
func testEncoding_singleNestedMessage() {
var nested = MessageTestType.NestedMessage()
nested.bb = 7
var a = MessageTestType()
a.singleNestedMessage = nested
XCTAssertEqual("single_nested_message {\n bb: 7\n}\n", a.textFormatString())
assertTextFormatEncode("single_nested_message {\n bb: 7\n}\n") {(o: inout MessageTestType) in
o.singleNestedMessage = nested
}
// Google permits reading a message field with or without the separating ':'
assertTextFormatDecodeSucceeds("single_nested_message: {bb:7}") {(o: MessageTestType) in
return o.singleNestedMessage.bb == 7
}
// Messages can be wrapped in {...} or <...>
assertTextFormatDecodeSucceeds("single_nested_message <bb:7>") {(o: MessageTestType) in
return o.singleNestedMessage.bb == 7
}
// Google permits reading a message field with or without the separating ':'
assertTextFormatDecodeSucceeds("single_nested_message: <bb:7>") {(o: MessageTestType) in
return o.singleNestedMessage.bb == 7
}
assertTextFormatDecodeFails("single_nested_message: a\n")
}
func testEncoding_singleForeignMessage() {
var foreign = Proto3ForeignMessage()
foreign.c = 88
var a = MessageTestType()
a.singleForeignMessage = foreign
XCTAssertEqual("single_foreign_message {\n c: 88\n}\n", a.textFormatString())
assertTextFormatEncode("single_foreign_message {\n c: 88\n}\n") {(o: inout MessageTestType) in o.singleForeignMessage = foreign }
do {
let message = try MessageTestType(textFormatString:"single_foreign_message: {\n c: 88\n}\n")
XCTAssertEqual(message.singleForeignMessage.c, 88)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("single_foreign_message: a\n")
}
func testEncoding_singleImportMessage() {
var importMessage = Proto3ImportMessage()
importMessage.d = -9
var a = MessageTestType()
a.singleImportMessage = importMessage
XCTAssertEqual("single_import_message {\n d: -9\n}\n", a.textFormatString())
assertTextFormatEncode("single_import_message {\n d: -9\n}\n") {(o: inout MessageTestType) in o.singleImportMessage = importMessage }
do {
let message = try MessageTestType(textFormatString:"single_import_message: {\n d: -9\n}\n")
XCTAssertEqual(message.singleImportMessage.d, -9)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("single_import_message: a\n")
}
func testEncoding_singleNestedEnum() throws {
var a = MessageTestType()
a.singleNestedEnum = .baz
XCTAssertEqual("single_nested_enum: BAZ\n", a.textFormatString())
assertTextFormatEncode("single_nested_enum: BAZ\n") {(o: inout MessageTestType) in
o.singleNestedEnum = .baz
}
assertTextFormatDecodeSucceeds("single_nested_enum:BAZ"){(o: MessageTestType) in
return o.singleNestedEnum == .baz
}
assertTextFormatDecodeSucceeds("single_nested_enum:1"){(o: MessageTestType) in
return o.singleNestedEnum == .foo
}
assertTextFormatDecodeSucceeds("single_nested_enum:2"){(o: MessageTestType) in
return o.singleNestedEnum == .bar
}
assertTextFormatDecodeFails("single_nested_enum: a\n")
assertTextFormatDecodeFails("single_nested_enum: FOOBAR")
assertTextFormatDecodeFails("single_nested_enum: \"BAR\"\n")
// Note: This implementation currently preserves numeric unknown
// enum values, unlike Google's C++ implementation, which considers
// it a parse error.
let b = try Proto3TestAllTypes(textFormatString: "single_nested_enum: 999\n")
XCTAssertEqual("single_nested_enum: 999\n", b.textFormatString())
}
func testEncoding_singleForeignEnum() {
var a = MessageTestType()
a.singleForeignEnum = .foreignBaz
XCTAssertEqual("single_foreign_enum: FOREIGN_BAZ\n", a.textFormatString())
assertTextFormatEncode("single_foreign_enum: FOREIGN_BAZ\n") {(o: inout MessageTestType) in o.singleForeignEnum = .foreignBaz }
assertTextFormatDecodeFails("single_foreign_enum: a\n")
}
func testEncoding_singleImportEnum() {
var a = MessageTestType()
a.singleImportEnum = .importBaz
XCTAssertEqual("single_import_enum: IMPORT_BAZ\n", a.textFormatString())
assertTextFormatEncode("single_import_enum: IMPORT_BAZ\n") {(o: inout MessageTestType) in o.singleImportEnum = .importBaz }
assertTextFormatDecodeFails("single_import_enum: a\n")
}
func testEncoding_singlePublicImportMessage() {
var publicImportMessage = Proto3PublicImportMessage()
publicImportMessage.e = -999999
var a = MessageTestType()
a.singlePublicImportMessage = publicImportMessage
XCTAssertEqual("single_public_import_message {\n e: -999999\n}\n", a.textFormatString())
assertTextFormatEncode("single_public_import_message {\n e: -999999\n}\n") {(o: inout MessageTestType) in o.singlePublicImportMessage = publicImportMessage }
do {
let message = try MessageTestType(textFormatString:"single_public_import_message: {\n e: -999999\n}\n")
XCTAssertEqual(message.singlePublicImportMessage.e, -999999)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("single_public_import_message: a\n")
}
//
// Repeated types
//
func testEncoding_repeatedInt32() {
var a = MessageTestType()
a.repeatedInt32 = [1, 2]
XCTAssertEqual("repeated_int32: [1, 2]\n", a.textFormatString())
assertTextFormatEncode("repeated_int32: [1, 2]\n") {(o: inout MessageTestType) in
o.repeatedInt32 = [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32: 1\n repeated_int32: 2\n") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32:[1, 2]") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32: [1] repeated_int32: 2\n") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32: 1 repeated_int32: [2]\n") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32:[]\nrepeated_int32: [1, 2]\nrepeated_int32:[]\n") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeSucceeds("repeated_int32:1\nrepeated_int32:2\n") {
(o: MessageTestType) in
return o.repeatedInt32 == [1, 2]
}
assertTextFormatDecodeFails("repeated_int32: 1\nrepeated_int32: a\n")
assertTextFormatDecodeFails("repeated_int32: [")
assertTextFormatDecodeFails("repeated_int32: [\n")
assertTextFormatDecodeFails("repeated_int32: [,]\n")
assertTextFormatDecodeFails("repeated_int32: [1\n")
assertTextFormatDecodeFails("repeated_int32: [1,\n")
assertTextFormatDecodeFails("repeated_int32: [1,]\n")
assertTextFormatDecodeFails("repeated_int32: [1,2\n")
assertTextFormatDecodeFails("repeated_int32: [1,2,]\n")
}
func testEncoding_repeatedInt64() {
assertTextFormatEncode("repeated_int64: [3, 4]\n") {(o: inout MessageTestType) in
o.repeatedInt64 = [3, 4]
}
assertTextFormatDecodeSucceeds("repeated_int64: 3\nrepeated_int64: 4\n") {(o: MessageTestType) in
return o.repeatedInt64 == [3, 4]
}
assertTextFormatDecodeFails("repeated_int64: 3\nrepeated_int64: a\n")
}
func testEncoding_repeatedUint32() {
assertTextFormatEncode("repeated_uint32: [5, 6]\n") {(o: inout MessageTestType) in
o.repeatedUint32 = [5, 6]
}
assertTextFormatDecodeFails("repeated_uint32: 5\nrepeated_uint32: a\n")
}
func testEncoding_repeatedUint64() {
assertTextFormatEncode("repeated_uint64: [7, 8]\n") {(o: inout MessageTestType) in
o.repeatedUint64 = [7, 8]
}
assertTextFormatDecodeSucceeds("repeated_uint64: 7\nrepeated_uint64: 8\n") {
$0.repeatedUint64 == [7, 8]
}
assertTextFormatDecodeFails("repeated_uint64: 7\nrepeated_uint64: a\n")
}
func testEncoding_repeatedSint32() {
assertTextFormatEncode("repeated_sint32: [9, 10]\n") {(o: inout MessageTestType) in
o.repeatedSint32 = [9, 10]
}
assertTextFormatDecodeFails("repeated_sint32: 9\nrepeated_sint32: a\n")
}
func testEncoding_repeatedSint64() {
assertTextFormatEncode("repeated_sint64: [11, 12]\n") {(o: inout MessageTestType) in
o.repeatedSint64 = [11, 12]
}
assertTextFormatDecodeFails("repeated_sint64: 11\nrepeated_sint64: a\n")
}
func testEncoding_repeatedFixed32() {
assertTextFormatEncode("repeated_fixed32: [13, 14]\n") {(o: inout MessageTestType) in
o.repeatedFixed32 = [13, 14]
}
assertTextFormatDecodeFails("repeated_fixed32: 13\nrepeated_fixed32: a\n")
}
func testEncoding_repeatedFixed64() {
assertTextFormatEncode("repeated_fixed64: [15, 16]\n") {(o: inout MessageTestType) in
o.repeatedFixed64 = [15, 16]
}
assertTextFormatDecodeFails("repeated_fixed64: 15\nrepeated_fixed64: a\n")
}
func testEncoding_repeatedSfixed32() {
assertTextFormatEncode("repeated_sfixed32: [17, 18]\n") {(o: inout MessageTestType) in
o.repeatedSfixed32 = [17, 18]
}
assertTextFormatDecodeFails("repeated_sfixed32: 17\nrepeated_sfixed32: a\n")
}
func testEncoding_repeatedSfixed64() {
assertTextFormatEncode("repeated_sfixed64: [19, 20]\n") {(o: inout MessageTestType) in
o.repeatedSfixed64 = [19, 20]
}
assertTextFormatDecodeFails("repeated_sfixed64: 19\nrepeated_sfixed64: a\n")
}
func testEncoding_repeatedFloat() {
assertTextFormatEncode("repeated_float: [21, 22]\n") {(o: inout MessageTestType) in
o.repeatedFloat = [21, 22]
}
assertTextFormatDecodeFails("repeated_float: 21\nrepeated_float: a\n")
}
func testEncoding_repeatedDouble() {
assertTextFormatEncode("repeated_double: [23, 24]\n") {(o: inout MessageTestType) in
o.repeatedDouble = [23, 24]
}
assertTextFormatEncode("repeated_double: [2.25, 2.5]\n") {(o: inout MessageTestType) in
o.repeatedDouble = [2.25, 2.5]
}
assertTextFormatDecodeFails("repeated_double: 23\nrepeated_double: a\n")
}
func testEncoding_repeatedBool() {
assertTextFormatEncode("repeated_bool: [true, false]\n") {(o: inout MessageTestType) in
o.repeatedBool = [true, false]
}
assertTextFormatDecodeSucceeds("repeated_bool: [true, false, True, False, t, f, 1, 0]") {
(o: MessageTestType) in
return o.repeatedBool == [true, false, true, false, true, false, true, false]
}
assertTextFormatDecodeFails("repeated_bool: true\nrepeated_bool: a\n")
}
func testEncoding_repeatedString() {
assertTextFormatDecodeSucceeds("repeated_string: \"abc\"\nrepeated_string: \"def\"\n") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeSucceeds("repeated_string: \"a\" \"bc\"\nrepeated_string: 'd' \"e\" \"f\"\n") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeSucceeds("repeated_string:[\"abc\", \"def\"]") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeSucceeds("repeated_string:[\"a\"\"bc\", \"d\" 'e' \"f\"]") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeSucceeds("repeated_string:[\"abc\", 'def']") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeSucceeds("repeated_string:[\"abc\"] repeated_string: \"def\"") {
(o: MessageTestType) in
return o.repeatedString == ["abc", "def"]
}
assertTextFormatDecodeFails("repeated_string:[\"abc\", \"def\",]")
assertTextFormatDecodeFails("repeated_string:[\"abc\"")
assertTextFormatDecodeFails("repeated_string:[\"abc\",")
assertTextFormatDecodeFails("repeated_string:[\"abc\",]")
assertTextFormatDecodeFails("repeated_string: \"abc\"]")
assertTextFormatDecodeFails("repeated_string: abc")
assertTextFormatEncode("repeated_string: \"abc\"\nrepeated_string: \"def\"\n") {(o: inout MessageTestType) in o.repeatedString = ["abc", "def"] }
}
func testEncoding_repeatedBytes() {
var a = MessageTestType()
a.repeatedBytes = [Data(), Data(bytes: [65, 66])]
XCTAssertEqual("repeated_bytes: \"\"\nrepeated_bytes: \"AB\"\n", a.textFormatString())
assertTextFormatEncode("repeated_bytes: \"\"\nrepeated_bytes: \"AB\"\n") {(o: inout MessageTestType) in
o.repeatedBytes = [Data(), Data(bytes: [65, 66])]
}
assertTextFormatDecodeSucceeds("repeated_bytes: \"\"\nrepeated_bytes: \"A\" \"B\"\n") {(o: MessageTestType) in
return o.repeatedBytes == [Data(), Data(bytes: [65, 66])]
}
assertTextFormatDecodeSucceeds("repeated_bytes: [\"\", \"AB\"]\n") {(o: MessageTestType) in
return o.repeatedBytes == [Data(), Data(bytes: [65, 66])]
}
assertTextFormatDecodeSucceeds("repeated_bytes: [\"\", \"A\" \"B\"]\n") {(o: MessageTestType) in
return o.repeatedBytes == [Data(), Data(bytes: [65, 66])]
}
}
func testEncoding_repeatedNestedMessage() {
var nested = MessageTestType.NestedMessage()
nested.bb = 7
var nested2 = nested
nested2.bb = -7
var a = MessageTestType()
a.repeatedNestedMessage = [nested, nested2]
XCTAssertEqual("repeated_nested_message {\n bb: 7\n}\nrepeated_nested_message {\n bb: -7\n}\n", a.textFormatString())
assertTextFormatEncode("repeated_nested_message {\n bb: 7\n}\nrepeated_nested_message {\n bb: -7\n}\n") {(o: inout MessageTestType) in o.repeatedNestedMessage = [nested, nested2] }
assertTextFormatDecodeSucceeds("repeated_nested_message: {\n bb: 7\n}\nrepeated_nested_message: {\n bb: -7\n}\n") {
(o: MessageTestType) in
return o.repeatedNestedMessage == [
MessageTestType.NestedMessage.with {$0.bb = 7},
MessageTestType.NestedMessage.with {$0.bb = -7}
]
}
assertTextFormatDecodeSucceeds("repeated_nested_message:[{bb: 7}, {bb: -7}]") {
(o: MessageTestType) in
return o.repeatedNestedMessage == [
MessageTestType.NestedMessage.with {$0.bb = 7},
MessageTestType.NestedMessage.with {$0.bb = -7}
]
}
assertTextFormatDecodeFails("repeated_nested_message {\n bb: 7\n}\nrepeated_nested_message {\n bb: a\n}\n")
}
func testEncoding_repeatedForeignMessage() {
var foreign = Proto3ForeignMessage()
foreign.c = 88
var foreign2 = foreign
foreign2.c = -88
var a = MessageTestType()
a.repeatedForeignMessage = [foreign, foreign2]
XCTAssertEqual("repeated_foreign_message {\n c: 88\n}\nrepeated_foreign_message {\n c: -88\n}\n", a.textFormatString())
assertTextFormatEncode("repeated_foreign_message {\n c: 88\n}\nrepeated_foreign_message {\n c: -88\n}\n") {(o: inout MessageTestType) in o.repeatedForeignMessage = [foreign, foreign2] }
do {
let message = try MessageTestType(textFormatString:"repeated_foreign_message: {\n c: 88\n}\nrepeated_foreign_message: {\n c: -88\n}\n")
XCTAssertEqual(message.repeatedForeignMessage[0].c, 88)
XCTAssertEqual(message.repeatedForeignMessage[1].c, -88)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("repeated_foreign_message {\n c: 88\n}\nrepeated_foreign_message {\n c: a\n}\n")
}
func testEncoding_repeatedImportMessage() {
var importMessage = Proto3ImportMessage()
importMessage.d = -9
var importMessage2 = importMessage
importMessage2.d = 999999
var a = MessageTestType()
a.repeatedImportMessage = [importMessage, importMessage2]
XCTAssertEqual("repeated_import_message {\n d: -9\n}\nrepeated_import_message {\n d: 999999\n}\n", a.textFormatString())
assertTextFormatEncode("repeated_import_message {\n d: -9\n}\nrepeated_import_message {\n d: 999999\n}\n") {(o: inout MessageTestType) in o.repeatedImportMessage = [importMessage, importMessage2] }
do {
let message = try MessageTestType(textFormatString:"repeated_import_message: {\n d: -9\n}\nrepeated_import_message: {\n d: 999999\n}\n")
XCTAssertEqual(message.repeatedImportMessage[0].d, -9)
XCTAssertEqual(message.repeatedImportMessage[1].d, 999999)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("repeated_import_message {\n d: -9\n}\nrepeated_import_message {\n d: a\n}\n")
}
func testEncoding_repeatedNestedEnum() {
assertTextFormatEncode("repeated_nested_enum: [BAR, BAZ]\n") {(o: inout MessageTestType) in
o.repeatedNestedEnum = [.bar, .baz]
}
assertTextFormatDecodeSucceeds("repeated_nested_enum: BAR repeated_nested_enum: BAZ") {
(o: MessageTestType) in
return o.repeatedNestedEnum == [.bar, .baz]
}
assertTextFormatDecodeSucceeds("repeated_nested_enum: [2, BAZ]") {
(o: MessageTestType) in
return o.repeatedNestedEnum == [.bar, .baz]
}
assertTextFormatDecodeSucceeds("repeated_nested_enum: [] repeated_nested_enum: [2] repeated_nested_enum: [BAZ] repeated_nested_enum: []") {
(o: MessageTestType) in
return o.repeatedNestedEnum == [.bar, .baz]
}
assertTextFormatDecodeFails("repeated_nested_enum: BAR\nrepeated_nested_enum: a\n")
}
func testEncoding_repeatedForeignEnum() {
assertTextFormatEncode("repeated_foreign_enum: [FOREIGN_BAR, FOREIGN_BAZ]\n") {(o: inout MessageTestType) in
o.repeatedForeignEnum = [.foreignBar, .foreignBaz]
}
assertTextFormatDecodeFails("repeated_foreign_enum: FOREIGN_BAR\nrepeated_foreign_enum: a\n")
}
func testEncoding_repeatedImportEnum() {
assertTextFormatEncode("repeated_import_enum: [IMPORT_BAR, IMPORT_BAZ]\n") {(o: inout MessageTestType) in
o.repeatedImportEnum = [.importBar, .importBaz]
}
assertTextFormatDecodeFails("repeated_import_enum: IMPORT_BAR\nrepeated_import_enum: a\n")
}
func testEncoding_repeatedPublicImportMessage() {
var publicImportMessage = Proto3PublicImportMessage()
publicImportMessage.e = -999999
var publicImportMessage2 = publicImportMessage
publicImportMessage2.e = 999999
var a = MessageTestType()
a.repeatedPublicImportMessage = [publicImportMessage, publicImportMessage2]
XCTAssertEqual("repeated_public_import_message {\n e: -999999\n}\nrepeated_public_import_message {\n e: 999999\n}\n", a.textFormatString())
assertTextFormatEncode("repeated_public_import_message {\n e: -999999\n}\nrepeated_public_import_message {\n e: 999999\n}\n") {(o: inout MessageTestType) in o.repeatedPublicImportMessage = [publicImportMessage, publicImportMessage2] }
assertTextFormatDecodeSucceeds("repeated_public_import_message <e: -999999> repeated_public_import_message <\n e: 999999\n>\n") {
(o: MessageTestType) in
return o.repeatedPublicImportMessage == [publicImportMessage, publicImportMessage2]
}
assertTextFormatDecodeSucceeds("repeated_public_import_message {e: -999999} repeated_public_import_message {\n e: 999999\n}\n") {
(o: MessageTestType) in
return o.repeatedPublicImportMessage == [publicImportMessage, publicImportMessage2]
}
assertTextFormatDecodeSucceeds("repeated_public_import_message [{e: -999999}, <e: 999999>]") {
(o: MessageTestType) in
return o.repeatedPublicImportMessage == [publicImportMessage, publicImportMessage2]
}
assertTextFormatDecodeSucceeds("repeated_public_import_message:[{e:999999},{e:-999999}]") {
(o: MessageTestType) in
return o.repeatedPublicImportMessage == [publicImportMessage2, publicImportMessage]
}
assertTextFormatDecodeFails("repeated_public_import_message:[{e:999999},{e:-999999},]")
do {
let message = try MessageTestType(textFormatString:"repeated_public_import_message: {\n e: -999999\n}\nrepeated_public_import_message: {\n e: 999999\n}\n")
XCTAssertEqual(message.repeatedPublicImportMessage[0].e, -999999)
XCTAssertEqual(message.repeatedPublicImportMessage[1].e, 999999)
} catch {
XCTFail("Presented error: \(error)")
}
assertTextFormatDecodeFails("repeated_public_import_message: a\n")
assertTextFormatDecodeFails("repeated_public_import_message: <e:99999}\n")
assertTextFormatDecodeFails("repeated_public_import_message:[{e:99999}")
assertTextFormatDecodeFails("repeated_public_import_message: {e:99999>\n")
}
func testEncoding_oneofUint32() {
var a = MessageTestType()
a.oneofUint32 = 99
XCTAssertEqual("oneof_uint32: 99\n", a.textFormatString())
assertTextFormatEncode("oneof_uint32: 99\n") {(o: inout MessageTestType) in o.oneofUint32 = 99 }
assertTextFormatDecodeFails("oneof_uint32: a\n")
}
//
// Various odd cases...
//
func testInvalidToken() {
assertTextFormatDecodeFails("optional_bool: true\n-5\n")
assertTextFormatDecodeFails("optional_bool: true!\n")
assertTextFormatDecodeFails("\"optional_bool\": true\n")
}
func testInvalidFieldName() {
assertTextFormatDecodeFails("invalid_field: value\n")
}
func testInvalidCapitalization() {
assertTextFormatDecodeFails("optionalgroup {\na: 15\n}\n")
assertTextFormatDecodeFails("OPTIONALgroup {\na: 15\n}\n")
assertTextFormatDecodeFails("Optional_Bool: true\n")
}
func testExplicitDelimiters() {
assertTextFormatDecodeSucceeds("single_int32:1,single_int64:3;single_uint32:4") {(o: MessageTestType) in
return o.singleInt32 == 1 && o.singleInt64 == 3 && o.singleUint32 == 4
}
assertTextFormatDecodeSucceeds("single_int32:1,\n") {(o: MessageTestType) in
return o.singleInt32 == 1
}
assertTextFormatDecodeSucceeds("single_int32:1;\n") {(o: MessageTestType) in
return o.singleInt32 == 1
}
}
//
// Multiple fields at once
//
private func configureLargeObject(_ o: inout MessageTestType) {
o.singleInt32 = 1
o.singleInt64 = 2
o.singleUint32 = 3
o.singleUint64 = 4
o.singleSint32 = 5
o.singleSint64 = 6
o.singleFixed32 = 7
o.singleFixed64 = 8
o.singleSfixed32 = 9
o.singleSfixed64 = 10
o.singleFloat = 11
o.singleDouble = 12
o.singleBool = true
o.singleString = "abc"
o.singleBytes = Data(bytes: [65, 66])
var nested = MessageTestType.NestedMessage()
nested.bb = 7
o.singleNestedMessage = nested
var foreign = Proto3ForeignMessage()
foreign.c = 88
o.singleForeignMessage = foreign
var importMessage = Proto3ImportMessage()
importMessage.d = -9
o.singleImportMessage = importMessage
o.singleNestedEnum = .baz
o.singleForeignEnum = .foreignBaz
o.singleImportEnum = .importBaz
var publicImportMessage = Proto3PublicImportMessage()
publicImportMessage.e = -999999
o.singlePublicImportMessage = publicImportMessage
o.repeatedInt32 = [1, 2]
o.repeatedInt64 = [3, 4]
o.repeatedUint32 = [5, 6]
o.repeatedUint64 = [7, 8]
o.repeatedSint32 = [9, 10]
o.repeatedSint64 = [11, 12]
o.repeatedFixed32 = [13, 14]
o.repeatedFixed64 = [15, 16]
o.repeatedSfixed32 = [17, 18]
o.repeatedSfixed64 = [19, 20]
o.repeatedFloat = [21, 22]
o.repeatedDouble = [23, 24]
o.repeatedBool = [true, false]
o.repeatedString = ["abc", "def"]
o.repeatedBytes = [Data(), Data(bytes: [65, 66])]
var nested2 = nested
nested2.bb = -7
o.repeatedNestedMessage = [nested, nested2]
var foreign2 = foreign
foreign2.c = -88
o.repeatedForeignMessage = [foreign, foreign2]
var importMessage2 = importMessage
importMessage2.d = 999999
o.repeatedImportMessage = [importMessage, importMessage2]
o.repeatedNestedEnum = [.bar, .baz]
o.repeatedForeignEnum = [.foreignBar, .foreignBaz]
o.repeatedImportEnum = [.importBar, .importBaz]
var publicImportMessage2 = publicImportMessage
publicImportMessage2.e = 999999
o.repeatedPublicImportMessage = [publicImportMessage, publicImportMessage2]
o.oneofUint32 = 99
}
func testMultipleFields() {
let expected: String = ("single_int32: 1\n"
+ "single_int64: 2\n"
+ "single_uint32: 3\n"
+ "single_uint64: 4\n"
+ "single_sint32: 5\n"
+ "single_sint64: 6\n"
+ "single_fixed32: 7\n"
+ "single_fixed64: 8\n"
+ "single_sfixed32: 9\n"
+ "single_sfixed64: 10\n"
+ "single_float: 11\n"
+ "single_double: 12\n"
+ "single_bool: true\n"
+ "single_string: \"abc\"\n"
+ "single_bytes: \"AB\"\n"
+ "single_nested_message {\n"
+ " bb: 7\n"
+ "}\n"
+ "single_foreign_message {\n"
+ " c: 88\n"
+ "}\n"
+ "single_import_message {\n"
+ " d: -9\n"
+ "}\n"
+ "single_nested_enum: BAZ\n"
+ "single_foreign_enum: FOREIGN_BAZ\n"
+ "single_import_enum: IMPORT_BAZ\n"
+ "single_public_import_message {\n"
+ " e: -999999\n"
+ "}\n"
+ "repeated_int32: [1, 2]\n"
+ "repeated_int64: [3, 4]\n"
+ "repeated_uint32: [5, 6]\n"
+ "repeated_uint64: [7, 8]\n"
+ "repeated_sint32: [9, 10]\n"
+ "repeated_sint64: [11, 12]\n"
+ "repeated_fixed32: [13, 14]\n"
+ "repeated_fixed64: [15, 16]\n"
+ "repeated_sfixed32: [17, 18]\n"
+ "repeated_sfixed64: [19, 20]\n"
+ "repeated_float: [21, 22]\n"
+ "repeated_double: [23, 24]\n"
+ "repeated_bool: [true, false]\n"
+ "repeated_string: \"abc\"\n"
+ "repeated_string: \"def\"\n"
+ "repeated_bytes: \"\"\n"
+ "repeated_bytes: \"AB\"\n"
+ "repeated_nested_message {\n"
+ " bb: 7\n"
+ "}\n"
+ "repeated_nested_message {\n"
+ " bb: -7\n"
+ "}\n"
+ "repeated_foreign_message {\n"
+ " c: 88\n"
+ "}\n"
+ "repeated_foreign_message {\n"
+ " c: -88\n"
+ "}\n"
+ "repeated_import_message {\n"
+ " d: -9\n"
+ "}\n"
+ "repeated_import_message {\n"
+ " d: 999999\n"
+ "}\n"
+ "repeated_nested_enum: [BAR, BAZ]\n"
+ "repeated_foreign_enum: [FOREIGN_BAR, FOREIGN_BAZ]\n"
+ "repeated_import_enum: [IMPORT_BAR, IMPORT_BAZ]\n"
+ "repeated_public_import_message {\n"
+ " e: -999999\n"
+ "}\n"
+ "repeated_public_import_message {\n"
+ " e: 999999\n"
+ "}\n"
+ "oneof_uint32: 99\n")
assertTextFormatEncode(expected, configure: configureLargeObject)
}
}
| mit | 52ce690ca3bf582ca7384a874c06e1bd | 42.868936 | 244 | 0.618754 | 4.329522 | false | true | false | false |
col/HAL | PromiseKit/Promise.swift | 1 | 12609 | import Foundation
private enum State<T> {
case Pending(Handlers)
case Fulfilled(@autoclosure () -> T) //TODO use plain T, once Swift compiler matures
case Rejected(Error)
}
public class Promise<T> {
private let barrier = dispatch_queue_create("org.promisekit.barrier", DISPATCH_QUEUE_CONCURRENT)
private var _state: State<T>
private var state: State<T> {
var result: State<T>?
dispatch_sync(barrier) { result = self._state }
return result!
}
public var rejected: Bool {
switch state {
case .Fulfilled, .Pending: return false
case .Rejected: return true
}
}
public var fulfilled: Bool {
switch state {
case .Rejected, .Pending: return false
case .Fulfilled: return true
}
}
public var pending: Bool {
switch state {
case .Rejected, .Fulfilled: return false
case .Pending: return true
}
}
/**
returns the fulfilled value unless the Promise is pending
or rejected in which case returns `nil`
*/
public var value: T? {
switch state {
case .Fulfilled(let value):
return value()
default:
return nil
}
}
/**
returns the rejected error unless the Promise is pending
or fulfilled in which case returns `nil`
*/
public var error: NSError? {
switch state {
case .Rejected(let error):
return error
default:
return nil
}
}
public init(_ body:(fulfill:(T) -> Void, reject:(NSError) -> Void) -> Void) {
_state = .Pending(Handlers())
let resolver = { (newstate: State<T>) -> Void in
var handlers = Array<()->()>()
dispatch_barrier_sync(self.barrier) {
switch self._state {
case .Pending(let Ω):
self._state = newstate
handlers = Ω.bodies
Ω.bodies.removeAll(keepCapacity: false)
default:
noop()
}
}
for handler in handlers { handler() }
}
body({ resolver(.Fulfilled($0)) }, { resolver(.Rejected(Error($0))) })
}
public class func defer() -> (promise:Promise, fulfill:(T) -> Void, reject:(NSError) -> Void) {
var f: ((T) -> Void)?
var r: ((NSError) -> Void)?
let p = Promise{ f = $0; r = $1 }
return (p, f!, r!)
}
public init(value: T) {
_state = .Fulfilled(value)
}
public init(error: NSError) {
_state = .Rejected(Error(error))
}
public func then<U>(onQueue q:dispatch_queue_t = dispatch_get_main_queue(), body:(T) -> U) -> Promise<U> {
return Promise<U>{ (fulfill, reject) in
let handler = { ()->() in
switch self.state {
case .Rejected(let error):
reject(error)
case .Fulfilled(let value):
dispatch_async(q) { fulfill(body(value())) }
case .Pending:
abort()
}
}
switch self.state {
case .Rejected, .Fulfilled:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
}
public func then<U>(onQueue q:dispatch_queue_t = dispatch_get_main_queue(), body:(T) -> Promise<U>) -> Promise<U> {
return Promise<U>{ (fulfill, reject) in
let handler = { ()->() in
switch self.state {
case .Rejected(let error):
reject(error)
case .Fulfilled(let value):
dispatch_async(q) {
let promise = body(value())
switch promise.state {
case .Rejected(let error):
reject(error)
case .Fulfilled(let value):
fulfill(value())
case .Pending(let handlers):
dispatch_barrier_sync(promise.barrier) {
handlers.append {
switch promise.state {
case .Rejected(let error):
reject(error)
case .Fulfilled(let value):
fulfill(value())
case .Pending:
abort()
}
}
}
}
}
case .Pending:
abort()
}
}
switch self.state {
case .Rejected, .Fulfilled:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
}
public func catch(onQueue q:dispatch_queue_t = dispatch_get_main_queue(), body:(NSError) -> T) -> Promise<T> {
return Promise<T>{ (fulfill, _) in
let handler = { ()->() in
switch self.state {
case .Rejected(let error):
dispatch_async(q) {
error.consumed = true
fulfill(body(error))
}
case .Fulfilled(let value):
fulfill(value())
case .Pending:
abort()
}
}
switch self.state {
case .Fulfilled, .Rejected:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
}
public func catch(onQueue q:dispatch_queue_t = dispatch_get_main_queue(), body:(NSError) -> Void) -> Void {
let handler = { ()->() in
switch self.state {
case .Rejected(let error):
dispatch_async(q) {
error.consumed = true
body(error)
}
case .Fulfilled:
noop()
case .Pending:
abort()
}
}
switch self.state {
case .Fulfilled, .Rejected:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
public func catch(onQueue q:dispatch_queue_t = dispatch_get_main_queue(), body:(NSError) -> Promise<T>) -> Promise<T> {
return Promise<T>{ (fulfill, reject) in
let handler = { ()->() in
switch self.state {
case .Fulfilled(let value):
fulfill(value())
case .Rejected(let error):
dispatch_async(q) {
error.consumed = true
let promise = body(error)
switch promise.state {
case .Fulfilled(let value):
fulfill(value())
case .Rejected(let error):
dispatch_async(q) { reject(error) }
case .Pending(let handlers):
dispatch_barrier_sync(promise.barrier) {
handlers.append {
switch promise.state {
case .Rejected(let error):
reject(error)
case .Fulfilled(let value):
fulfill(value())
case .Pending:
abort()
}
}
}
}
}
case .Pending:
abort()
}
}
switch self.state {
case .Fulfilled, .Rejected:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
}
//FIXME adding the queue parameter prevents compilation with Xcode 6.0.1
public func finally(/*onQueue q:dispatch_queue_t = dispatch_get_main_queue(),*/ body:()->()) -> Promise<T> {
let q = dispatch_get_main_queue()
return Promise<T>{ (fulfill, reject) in
let handler = { ()->() in
switch self.state {
case .Fulfilled(let value):
dispatch_async(q) {
body()
fulfill(value())
}
case .Rejected(let error):
dispatch_async(q) {
body()
reject(error)
}
case .Pending:
abort()
}
}
switch self.state {
case .Fulfilled, .Rejected:
handler()
case .Pending(let handlers):
dispatch_barrier_sync(self.barrier) {
handlers.append(handler)
}
}
}
}
/**
Immediate resolution of body if the promise is fulfilled.
Please note, there are good reasons that `then` does not call `body`
immediately if the promise is already fulfilled. If you don’t understand
the implications of unleashing zalgo, you should not under any
cirumstances use this function!
*/
public func thenUnleashZalgo(body:(T)->Void) -> Void {
if let obj = value {
body(obj)
} else {
then(body)
}
}
}
private class Error : NSError {
var consumed: Bool = false //TODO strictly, should be atomic
init(_ error: NSError) {
if error is Error {
// we always make a new Error, this allows users to pass
// the reject function from a Promise constructor as a
// catch handler without the error being considered
// consumed. We do this ourselves in when()
(error as Error).consumed = true
}
super.init(domain: error.domain, code: error.code, userInfo: error.userInfo)
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
deinit {
if !consumed {
NSLog("%@", "PromiseKit: Unhandled error: \(self)")
}
}
}
/**
When accessing handlers from the State enum, the array
must not be a copy or we stop being thread-safe. Hence
this class.
*/
private class Handlers: SequenceType {
var bodies: [()->()] = []
func append(body: ()->()) {
bodies.append(body)
}
func generate() -> IndexingGenerator<[()->()]> {
return bodies.generate()
}
var count: Int {
return bodies.count
}
}
extension Promise: DebugPrintable {
public var debugDescription: String {
var state: State<T>?
dispatch_sync(barrier) {
state = self._state
}
switch state! {
case .Pending(let handlers):
var count: Int?
dispatch_sync(barrier) {
count = handlers.count
}
return "Promise: Pending with \(count!) handlers"
case .Fulfilled(let value):
return "Promise: Fulfilled with value: \(value())"
case .Rejected(let error):
return "Promise: Rejected with error: \(error)"
}
}
}
func dispatch_promise<T>(/*to q:dispatch_queue_t = dispatch_get_global_queue(0, 0),*/ body:() -> AnyObject) -> Promise<T> {
let q = dispatch_get_global_queue(0, 0)
return Promise<T> { (fulfill, reject) in
dispatch_async(q) {
let obj: AnyObject = body()
if obj is NSError {
reject(obj as NSError)
} else {
fulfill(obj as T)
}
}
}
}
| mit | 7135afc0c2b280762e69e1327a4626f2 | 29.816626 | 123 | 0.44835 | 5.113185 | false | false | false | false |
dkarsh/SwiftGoal | SwiftGoal/Views/EditMatchViewController.swift | 2 | 8470 | //
// EditMatchViewController.swift
// SwiftGoal
//
// Created by Martin Richter on 22/06/15.
// Copyright (c) 2015 Martin Richter. All rights reserved.
//
import UIKit
import ReactiveCocoa
import SnapKit
class EditMatchViewController: UIViewController {
private let viewModel: EditMatchViewModel
private weak var homeGoalsLabel: UILabel!
private weak var goalSeparatorLabel: UILabel!
private weak var awayGoalsLabel: UILabel!
private weak var homeGoalsStepper: UIStepper!
private weak var awayGoalsStepper: UIStepper!
private weak var homePlayersButton: UIButton!
private weak var awayPlayersButton: UIButton!
private var saveAction: CocoaAction
private let saveButtonItem: UIBarButtonItem
// MARK: Lifecycle
init(viewModel: EditMatchViewModel) {
self.viewModel = viewModel
self.saveAction = CocoaAction(viewModel.saveAction, { _ in return () })
self.saveButtonItem = UIBarButtonItem(
barButtonSystemItem: .Save,
target: self.saveAction,
action: CocoaAction.selector
)
super.init(nibName: nil, bundle: nil)
// Set up navigation item
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .Cancel,
target: self,
action: #selector(cancelButtonTapped)
)
navigationItem.rightBarButtonItem = self.saveButtonItem
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Lifecycle
override func loadView() {
let view = UIView()
view.backgroundColor = UIColor.whiteColor()
let labelFont = UIFont(name: "OpenSans-Semibold", size: 70)
let homeGoalsLabel = UILabel()
homeGoalsLabel.font = labelFont
view.addSubview(homeGoalsLabel)
self.homeGoalsLabel = homeGoalsLabel
let goalSeparatorLabel = UILabel()
goalSeparatorLabel.font = labelFont
goalSeparatorLabel.text = ":"
view.addSubview(goalSeparatorLabel)
self.goalSeparatorLabel = goalSeparatorLabel
let awayGoalsLabel = UILabel()
awayGoalsLabel.font = labelFont
view.addSubview(awayGoalsLabel)
self.awayGoalsLabel = awayGoalsLabel
let homeGoalsStepper = UIStepper()
view.addSubview(homeGoalsStepper)
self.homeGoalsStepper = homeGoalsStepper
let awayGoalsStepper = UIStepper()
view.addSubview(awayGoalsStepper)
self.awayGoalsStepper = awayGoalsStepper
let homePlayersButton = UIButton(type: .System)
homePlayersButton.titleLabel?.font = UIFont(name: "OpenSans", size: 15)
homePlayersButton.addTarget(self,
action: #selector(homePlayersButtonTapped),
forControlEvents: .TouchUpInside
)
view.addSubview(homePlayersButton)
self.homePlayersButton = homePlayersButton
let awayPlayersButton = UIButton(type: .System)
awayPlayersButton.titleLabel?.font = UIFont(name: "OpenSans", size: 15)
awayPlayersButton.addTarget(self,
action: #selector(awayPlayersButtonTapped),
forControlEvents: .TouchUpInside
)
view.addSubview(awayPlayersButton)
self.awayPlayersButton = awayPlayersButton
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
makeConstraints()
}
// MARK: Bindings
private func bindViewModel() {
self.title = viewModel.title
// Initial values
homeGoalsStepper.value = Double(viewModel.homeGoals.value)
awayGoalsStepper.value = Double(viewModel.awayGoals.value)
viewModel.homeGoals <~ homeGoalsStepper.signalProducer()
viewModel.awayGoals <~ awayGoalsStepper.signalProducer()
viewModel.formattedHomeGoals.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] formattedHomeGoals in
self?.homeGoalsLabel.text = formattedHomeGoals
})
viewModel.formattedAwayGoals.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] formattedAwayGoals in
self?.awayGoalsLabel.text = formattedAwayGoals
})
viewModel.homePlayersString.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] homePlayersString in
self?.homePlayersButton.setTitle(homePlayersString, forState: .Normal)
})
viewModel.awayPlayersString.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] awayPlayersString in
self?.awayPlayersButton.setTitle(awayPlayersString, forState: .Normal)
})
viewModel.inputIsValid.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] inputIsValid in
self?.saveButtonItem.enabled = inputIsValid
})
viewModel.saveAction.events.observeNext({ [weak self] event in
switch event {
case let .Next(success):
if success {
self?.dismissViewControllerAnimated(true, completion: nil)
} else {
self?.presentErrorMessage("The match could not be saved.")
}
case let .Failed(error):
self?.presentErrorMessage(error.localizedDescription)
default:
return
}
})
}
// MARK: Layout
private func makeConstraints() {
let superview = self.view
homeGoalsLabel.snp_makeConstraints { make in
make.trailing.equalTo(goalSeparatorLabel.snp_leading).offset(-10)
make.baseline.equalTo(goalSeparatorLabel.snp_baseline)
}
goalSeparatorLabel.snp_makeConstraints { make in
make.centerX.equalTo(superview.snp_centerX)
make.centerY.equalTo(superview.snp_centerY).offset(-50)
}
awayGoalsLabel.snp_makeConstraints { make in
make.leading.equalTo(goalSeparatorLabel.snp_trailing).offset(10)
make.baseline.equalTo(goalSeparatorLabel.snp_baseline)
}
homeGoalsStepper.snp_makeConstraints { make in
make.top.equalTo(goalSeparatorLabel.snp_bottom).offset(10)
make.trailing.equalTo(homeGoalsLabel.snp_trailing)
}
awayGoalsStepper.snp_makeConstraints { make in
make.top.equalTo(goalSeparatorLabel.snp_bottom).offset(10)
make.leading.equalTo(awayGoalsLabel.snp_leading)
}
homePlayersButton.snp_makeConstraints { make in
make.top.equalTo(homeGoalsStepper.snp_bottom).offset(30)
make.leading.greaterThanOrEqualTo(superview.snp_leadingMargin)
make.trailing.equalTo(homeGoalsLabel.snp_trailing)
}
awayPlayersButton.snp_makeConstraints { make in
make.top.equalTo(awayGoalsStepper.snp_bottom).offset(30)
make.leading.equalTo(awayGoalsLabel.snp_leading)
make.trailing.lessThanOrEqualTo(superview.snp_trailingMargin)
}
}
// MARK: User Interaction
func cancelButtonTapped() {
dismissViewControllerAnimated(true, completion: nil)
}
func homePlayersButtonTapped() {
let homePlayersViewModel = viewModel.manageHomePlayersViewModel()
let homePlayersViewController = ManagePlayersViewController(viewModel: homePlayersViewModel)
self.navigationController?.pushViewController(homePlayersViewController, animated: true)
}
func awayPlayersButtonTapped() {
let awayPlayersViewModel = viewModel.manageAwayPlayersViewModel()
let awayPlayersViewController = ManagePlayersViewController(viewModel: awayPlayersViewModel)
self.navigationController?.pushViewController(awayPlayersViewController, animated: true)
}
// MARK: Private Helpers
func presentErrorMessage(message: String) {
let alertController = UIAlertController(
title: "Oops!",
message: message,
preferredStyle: .Alert
)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | ee4bc522f1268ba8b23210f17104156d | 33.291498 | 100 | 0.657143 | 5.09627 | false | false | false | false |
ffreling/pigeon | Pigeon/Pigeon/PSettingsViewController.swift | 1 | 6160 | //
// ViewController.swift
// Pigeon
//
// Created by Fabien on 2014-10-18.
// Copyright (c) 2014 Fabien. All rights reserved.
//
import Foundation
import Cocoa
class PSettingsViewController: NSViewController {
@IBOutlet var imapServer: NSTextField!
@IBOutlet var username: NSTextField!
@IBOutlet var password: NSSecureTextField!
var dockTile: NSDockTile!
var session: MCOIMAPSession!
override func awakeFromNib() {
let defaults = NSUserDefaults.standardUserDefaults()
let server = defaults.stringForKey("imapServer")
let username = defaults.stringForKey("username")
if let s = server {
self.imapServer.stringValue = s
}
if let uname = username {
self.username.stringValue = uname
}
self.dockTile = NSApp.dockTile
if server != nil && username != nil {
println("Trying to access password for server \(server!) and user \(username!)")
let password = self.passwordForServer(server: server!, username: username!)
if (password != nil) {
self.password.stringValue = password!
} else {
self.password.stringValue = ""
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func connect(sender: NSButton) {
self.session = MCOIMAPSession()
session.hostname = self.imapServer.stringValue
session.port = 993
session.username = self.username.stringValue
session.password = self.password.stringValue
session.connectionType = MCOConnectionType.TLS
println("connect: host = \(self.imapServer.stringValue)")
println("connect: username = \(self.username.stringValue)")
println("connect: password = \(self.password.stringValue)")
let op: MCOIMAPOperation = self.session.checkAccountOperation()
op.start({ (error: NSError!) -> Void in
if error != nil {
println("Could not connect.")
self.session = nil;
} else {
println("Connection successful.")
self.fetchMessages()
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(self.imapServer.stringValue, forKey: "imapServer")
defaults.setValue(self.username.stringValue, forKey: "username")
if !defaults.synchronize() {
println("Could not save credentials.")
}
self.savePassword(self.password.stringValue,
server: self.imapServer.stringValue,
username: self.username.stringValue)
}
})
}
// MARK: - Password
func passwordForServer(#server: NSString, username: NSString) -> String? {
var passwordLength: UInt32 = 0
var passwordData: UnsafeMutablePointer<Void> = nil
let status = SecKeychainFindInternetPassword(nil,
UInt32(server.length), server.UTF8String,
0, nil, /* security domain */
UInt32(username.length), username.UTF8String,
0, nil, /* path */
0, /* port */
SecProtocolType(kSecProtocolTypeIMAP),
SecAuthenticationType(kSecAuthenticationTypeDefault),
&passwordLength, &passwordData,
nil) /* itemRef */
if status != errSecSuccess {
println("Could not find password.")
return nil
}
let password = NSString(bytes: passwordData, length: Int(passwordLength), encoding: NSUTF8StringEncoding)
SecKeychainItemFreeContent(nil, passwordData);
return password
}
func savePassword(password: String, server: String, username: String) {
let password_ns: NSString = password
let server_ns: NSString = server
let username_ns: NSString = username
let status = SecKeychainAddInternetPassword(nil, /* default keychain */
UInt32(server_ns.length), server_ns.UTF8String,
0, nil, /* security domain */
UInt32(username_ns.length), username_ns.UTF8String,
0, nil, /* path */
0, /* port */
SecProtocolType(kSecProtocolTypeIMAP),
SecAuthenticationType(kSecAuthenticationTypeDefault),
UInt32(password_ns.length), password_ns.UTF8String,
nil)
if status != errSecSuccess {
println("Could not save password.")
let msg = SecCopyErrorMessageString(status, nil)
println("\(msg)")
}
}
// MARK: - Messages
func fetchMessages() {
let requestKind = MCOIMAPMessagesRequestKind.Headers | MCOIMAPMessagesRequestKind.Flags
let folder = "INBOX"
let uids = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))
let fetchOperation = self.session.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)
fetchOperation.start({ (err: NSError!, fetchedMessages: [AnyObject]!, indexSet: MCOIndexSet!) -> Void in
if err != nil {
println("Error downloading message headers: \(err)")
}
println("Inbox contains \(fetchedMessages.count) emails.")
let msgs = fetchedMessages as [MCOIMAPMessage]
let unreads = msgs.filter({ (includeElement: MCOIMAPMessage) -> Bool in
return (includeElement.flags & MCOMessageFlag.Seen) == nil
})
println("\(unreads.count) unread emails.")
if unreads.count > 0 {
self.dockTile.badgeLabel = "\(unreads.count)"
} else {
self.dockTile.badgeLabel = nil
}
})
}
}
| bsd-2-clause | 2d6ef74fb87993f1f498b398bad88a93 | 31.251309 | 116 | 0.580519 | 4.963739 | false | false | false | false |
alecthomas/EVReflection | EVReflection/EVReflectionTests/EVReflectionJsonTests.swift | 1 | 5698 | //
// EVReflectionJsonTests.swift
// EVReflection
//
// Created by Edwin Vermeer on 6/15/15.
// Copyright (c) 2015 evict. All rights reserved.
//
import UIKit
import XCTest
class User: EVObject {
var id: Int = 0
var name: String = ""
var email: String?
var company: Company?
var friends: [User]? = []
}
class Company: EVObject {
var name: String = ""
var address: String?
}
/**
Testing EVReflection for Json
*/
class EVReflectionJsonTests: XCTestCase {
/**
For now nothing to setUp
*/
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
/**
For now nothing to tearDown
*/
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testJsonArray() {
let jsonDictOriginal:String = "[{\"id\": 27, \"name\": \"Bob Jefferson\"}, {\"id\": 29, \"name\": \"Jen Jackson\"}]"
let array:[User] = EVReflection.arrayFromJson(User(), json: jsonDictOriginal)
print("Object array from json string: \n\(array)\n\n")
XCTAssertTrue(array.count == 2, "should have 2 Users")
XCTAssertTrue(array[0].id == 27, "id should have been set to 27")
XCTAssertTrue(array[0].name == "Bob Jefferson", "name should have been set to Bob Jefferson")
XCTAssertTrue(array[1].id == 29, "id should have been set to 29")
XCTAssertTrue(array[1].name == "Jen Jackson", "name should have been set to Jen Jackson")
}
func testJsonUser() {
let json:String = "{\"id\": 24, \"friends\": {}}"
let user = User(json: json)
XCTAssertTrue(user.id == 24, "id should have been set to 24")
XCTAssertTrue(user.friends?.count == 0, "friends should have 0 users")
}
func testJsonObject(){
let jsonDictOriginal = [
"id": 24,
"name": "John Appleseed",
"email": "[email protected]",
"company": [
"name": "Apple",
"address": "1 Infinite Loop, Cupertino, CA"
],
"friends": [
["id": 27, "name": "Bob Jefferson"],
["id": 29, "name": "Jen Jackson"]
]
]
print("Initial dictionary:\n\(jsonDictOriginal)\n\n")
let userOriginal = User(dictionary: jsonDictOriginal)
validateUser(userOriginal)
let jsonString = userOriginal.toJsonString()
print("JSON string from dictionary: \n\(jsonString)\n\n")
let userRegenerated = User(json:jsonString)
validateUser(userRegenerated)
if userOriginal == userRegenerated {
XCTAssert(true, "Success")
} else {
XCTAssert(false, "Faileure")
}
}
func validateUser(user:User?) {
print("Validate user: \n\(user)\n\n")
XCTAssertTrue(user?.id == 24, "id should have been set to 24")
XCTAssertTrue(user?.name == "John Appleseed", "name should have been set to John Appleseed")
XCTAssertTrue(user?.email == "[email protected]", "email should have been set to [email protected]")
XCTAssertNotNil(user?.company, "company should not be nil")
print("company = \(user?.company)\n")
XCTAssertTrue(user?.company?.name == "Apple", "company name should have been set to Apple")
print("company name = \(user?.company?.name)\n")
XCTAssertTrue(user?.company?.address == "1 Infinite Loop, Cupertino, CA", "company address should have been set to 1 Infinite Loop, Cupertino, CA")
XCTAssertNotNil(user?.friends, "friends should not be nil")
XCTAssertTrue(user?.friends!.count == 2, "friends should have 2 Users")
if user?.friends!.count == 2 {
XCTAssertTrue(user!.friends![0].id == 27, "friend 1 id should be 27")
XCTAssertTrue(user!.friends![0].name == "Bob Jefferson", "friend 1 name should be Bob Jefferson")
XCTAssertTrue(user!.friends![1].id == 29, "friend 2 id should be 29")
XCTAssertTrue(user!.friends![1].name == "Jen Jackson", "friend 2 name should be Jen Jackson")
}
}
func testTypeJsonAllString() {
let json:String = "{\"myString\":\"1\", \"myInt\":\"2\", \"myFloat\":\"2.1\", \"myBool\":\"1\"}"
let a = TestObject4(json: json)
XCTAssertEqual(a.myString, "1", "myString should contain 1")
XCTAssertEqual(a.myInt, 2, "myInt should contain 2")
XCTAssertEqual(a.myFloat, 2.1, "myFloat should contain 2.1")
XCTAssertEqual(a.myBool, true, "myBool should contain true")
}
func testTypeJson2AllNumeric() {
let json:String = "{\"myString\":1, \"myInt\":2, \"myFloat\":2.1, \"myBool\":1}"
let a = TestObject4(json: json)
XCTAssertEqual(a.myString, "1", "myString should contain 1")
XCTAssertEqual(a.myInt, 2, "myInt should contain 2")
XCTAssertEqual(a.myFloat, 2.1, "myFloat should contain 2.1")
XCTAssertEqual(a.myBool, true, "myBool should contain true")
}
func testTypeJsonInvalid() {
let json:String = "{\"myString\":test, \"myInt\":test, \"myFloat\":test, \"myBool\":false}"
let a = TestObject4(json: json)
XCTAssertEqual(a.myString, "", "myString should contain 1")
XCTAssertEqual(a.myInt, 0, "myInt should contain 0")
XCTAssertEqual(a.myFloat, 0, "myFloat should contain 2.1")
XCTAssertEqual(a.myBool, true, "myBool should contain true")
}
}
| mit | 1fd5cd012c0fab381e20d95a679e7c45 | 37.241611 | 155 | 0.594595 | 4.090452 | false | true | false | false |
shridharmalimca/LocationTracking | LocationTracking/LocationTracking/LocationManagerHelper.swift | 1 | 9018 | import UIKit
import CoreLocation
class LocationManagerHelper: NSObject {
let locationManager = CLLocationManager()
static let sharedInstance = LocationManagerHelper()
var latitude = Double()
var longitude = Double()
var userLocation = CLLocation()
var speedInKmPerHour: Double = 0.0
var previousSpeedInKmPerHour: Double = 0.0
var timer = Timer()
var isTimerSetForSpeed: Bool = false
var isSpeedChanged: Bool = false
var currentTimeInterval: Int = 0
var nextTimeInterval:Int = 0
public func updateUserLocation() {
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
public func stopLocationUpdate() {
locationManager.stopUpdatingLocation()
}
public func getLocation(latitude: Double, longitude: Double) -> CLLocation {
return CLLocation(latitude: latitude, longitude: longitude)
}
public func locationUpdatesAsPerCalculatedSpeedOfVehicle() {
// Manual testing for speed using Textfield on the home view controller
/* if speedInKmPerHour != previousSpeedInKmPerHour && previousSpeedInKmPerHour > 0.0 {
isSpeedChanged = true
} else {
isSpeedChanged = false
}
*/
if isSpeedChanged {
if (speedInKmPerHour > 0 || speedInKmPerHour < 30) && previousSpeedInKmPerHour < 30 {
if speedInKmPerHour > 30 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if (speedInKmPerHour > 30 || speedInKmPerHour < 60) && previousSpeedInKmPerHour < 60 {
if speedInKmPerHour > 60 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if (speedInKmPerHour > 60 || speedInKmPerHour < 60) && previousSpeedInKmPerHour < 80 {
if speedInKmPerHour > 80 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else if previousSpeedInKmPerHour >= 80 || previousSpeedInKmPerHour >= 60 && speedInKmPerHour < 30 {
isTimerSetForSpeed = false
} else if (speedInKmPerHour > 80 || speedInKmPerHour < 80) && previousSpeedInKmPerHour < 500 {
if speedInKmPerHour > 80 {
isTimerSetForSpeed = false
} else {
isTimerSetForSpeed = true
}
} else {
isTimerSetForSpeed = false
}
}
switch speedInKmPerHour {
case 0..<30:
// capture location after 5 mins
print("0..<30 KM/h")
if (!isTimerSetForSpeed) {
stopTimer()
setTimer(timeInterval: 5)// 300) // 60 * 5
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 300
nextTimeInterval = 120
}
case 30..<60:
// capture location after 2 mins
print("30..<60 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 2) //120) // 60 * 2
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 120
nextTimeInterval = 60
} else {
}
case 60..<80:
// capture location after 1 mins
print("60..<80 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 1)// 60)
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 60
nextTimeInterval = 30
}
case 80..<500:
// capture location after 30 secs
print("80..<500 KM/h")
if !isTimerSetForSpeed {
stopTimer()
setTimer(timeInterval: 30) // 30 sec
previousSpeedInKmPerHour = speedInKmPerHour
currentTimeInterval = 30
nextTimeInterval = 60
}
default:
print("Device is at ideal position or invalid speed found")
}
}
func setTimer(timeInterval: TimeInterval) {
isTimerSetForSpeed = true
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(captureLocation), userInfo: nil, repeats: true)
}
func stopTimer() {
timer.invalidate()
isTimerSetForSpeed = false
}
func captureLocation() {
saveUserLocationInFile()
// Save user location in DB
saveUserLocationInDB()
}
//MARK:- Save User Location In File
func saveUserLocationInFile() {
let fileManager = FileManager.default
let dir: URL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last!
let fileurl = dir.appendingPathComponent("locations.txt")
let headingText = "\t\t Time \t\t\t\t Latitude \t\t\t Longitude \t\t\t Current time interval \t\t Next time interval \n"
let separator = "--------------------------------------------------------------------------------------------------------------------------------"
let contentToWrite = " \(headingText) \(Date().addingTimeInterval(0)) \t \(latitude) \t\t\t \(longitude) \t\t\t\t\t \(currentTimeInterval) \t\t\t\t\t\t \(nextTimeInterval) \n \(separator) \n"
let data = contentToWrite.data(using: .utf8, allowLossyConversion: false)!
if fileManager.fileExists(atPath: fileurl.path) {
do {
let fileHandle = try FileHandle(forWritingTo: fileurl)
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
} catch let error {
print("file handle failed \(error.localizedDescription)")
}
} else {
do {
_ = try data.write(to: fileurl, options: .atomic)
} catch let error {
print("cant write \(error.localizedDescription)")
}
}
readFile()
}
func readFile() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask , true)
let docDir = path[0]
let sampleFilePath = docDir.appendingFormat("/locations.txt")
do {
let contentOfFile = try String(contentsOfFile: sampleFilePath, encoding: .utf8)
print("file content is: \(contentOfFile)")
} catch {
print("Error while read file")
}
}
// MARK:- Save User Location In DB
func saveUserLocationInDB() {
print("saveUserLocationInDB")
let objDBHelper = DBHelper.instance
objDBHelper.saveLocationUpdatedDataInLocalDB(time: userLocation.timestamp, latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, currentTimeInterval: currentTimeInterval, nextTimeInterval: nextTimeInterval, speed: speedInKmPerHour)
}
}
// MARK:- CLLocationManagerDelegate
extension LocationManagerHelper: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLocation = manager.location {
latitude = (manager.location?.coordinate.latitude)!
longitude = (manager.location?.coordinate.longitude)!
print("latitude :\(latitude)")
print("longitude :\(longitude)")
print("time stamp: \(String(describing: currentLocation.timestamp))")
// location Manager return speed in mps(meter per second)
let speedInMeterPerSecond = currentLocation.speed
// formula for calculate meter per second to km/h.
// km/h = mps * 3.6
// 5m/sec = (5 * 3.6) = 18 km/h
speedInKmPerHour = (speedInMeterPerSecond * 3.6)
// print("speed \(speedInKmPerHour) Km/h")
if speedInKmPerHour != previousSpeedInKmPerHour && previousSpeedInKmPerHour > 0.0 {
isSpeedChanged = true
} else {
isSpeedChanged = false
}
locationUpdatesAsPerCalculatedSpeedOfVehicle()
}
// Create a location
userLocation = CLLocation(latitude: latitude, longitude: longitude)
// print("User location is \(userLocation)")
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to get the current location of user \(error.localizedDescription)")
}
}
| mit | d685d03a9e56808a3dc40284aa5ac75c | 40.366972 | 275 | 0.576403 | 5.115145 | false | false | false | false |
drewg233/SlackyBeaver | Example/Pods/SwiftyBeaver/Sources/SBPlatformDestination.swift | 1 | 23456 | //
// SBPlatformDestination
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger on 22.01.16.
// Copyright © 2016 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
// platform-dependent import frameworks to get device details
// valid values for os(): OSX, iOS, watchOS, tvOS, Linux
// in Swift 3 the following were added: FreeBSD, Windows, Android
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
var DEVICE_MODEL: String {
get {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
#else
let DEVICE_MODEL = ""
#endif
#if os(iOS) || os(tvOS)
var DEVICE_NAME = UIDevice.current.name
#else
// under watchOS UIDevice is not existing, http://apple.co/26ch5J1
let DEVICE_NAME = ""
#endif
public class SBPlatformDestination: BaseDestination {
public var appID = ""
public var appSecret = ""
public var encryptionKey = ""
public var analyticsUserName = "" // user email, ID, name, etc.
public var analyticsUUID: String { return uuid }
// when to send to server
public struct SendingPoints {
public var verbose = 0
public var debug = 1
public var info = 5
public var warning = 8
public var error = 10
public var threshold = 10 // send to server if points reach that value
}
public var sendingPoints = SendingPoints()
public var showNSLog = false // executes toNSLog statements to debug the class
var points = 0
public var serverURL = URL(string: "https://api.swiftybeaver.com/api/entries/") // optional
public var entriesFileURL = URL(fileURLWithPath: "") // not optional
public var sendingFileURL = URL(fileURLWithPath: "")
public var analyticsFileURL = URL(fileURLWithPath: "")
private let minAllowedThreshold = 1 // over-rules SendingPoints.Threshold
private let maxAllowedThreshold = 1000 // over-rules SendingPoints.Threshold
private var sendingInProgress = false
private var initialSending = true
// analytics
var uuid = ""
// destination
override public var defaultHashValue: Int {return 3}
let fileManager = FileManager.default
let isoDateFormatter = DateFormatter()
/// init platform with default internal filenames
public init(appID: String, appSecret: String, encryptionKey: String,
entriesFileName: String = "sbplatform_entries.json",
sendingfileName: String = "sbplatform_entries_sending.json",
analyticsFileName: String = "sbplatform_analytics.json") {
super.init()
self.appID = appID
self.appSecret = appSecret
self.encryptionKey = encryptionKey
// setup where to write the json files
var baseURL: URL?
#if os(OSX)
if let url = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
baseURL = url
// try to use ~/Library/Application Support/APP NAME instead of ~/Library/Application Support
if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String {
do {
if let appURL = baseURL?.appendingPathComponent(appName, isDirectory: true) {
try fileManager.createDirectory(at: appURL,
withIntermediateDirectories: true, attributes: nil)
baseURL = appURL
}
} catch {
// it is too early in the class lifetime to be able to use toNSLog()
print("Warning! Could not create folder ~/Library/Application Support/\(appName).")
}
}
}
#else
#if os(tvOS)
// tvOS can just use the caches directory
if let url = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
baseURL = url
}
#elseif os(Linux)
// Linux is using /var/cache
let baseDir = "/var/cache/"
entriesFileURL = URL(fileURLWithPath: baseDir + entriesFileName)
sendingFileURL = URL(fileURLWithPath: baseDir + sendingfileName)
analyticsFileURL = URL(fileURLWithPath: baseDir + analyticsFileName)
#else
// iOS and watchOS are using the app’s document directory
if let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
baseURL = url
}
#endif
#endif
#if os(Linux)
// get, update loaded and save analytics data to file on start
let dict = analytics(analyticsFileURL, update: true)
let _ = saveDictToFile(dict, url: analyticsFileURL)
#else
if let baseURL = baseURL {
// is just set for everything but not Linux
entriesFileURL = baseURL.appendingPathComponent(entriesFileName,
isDirectory: false)
sendingFileURL = baseURL.appendingPathComponent(sendingfileName,
isDirectory: false)
analyticsFileURL = baseURL.appendingPathComponent(analyticsFileName,
isDirectory: false)
// get, update loaded and save analytics data to file on start
let dict = analytics(analyticsFileURL, update: true)
let _ = saveDictToFile(dict, url: analyticsFileURL)
}
#endif
}
// append to file, each line is a JSON dict
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
file: String, function: String, line: Int) -> String? {
var jsonString: String?
let dict: [String: Any] = [
"timestamp": Date().timeIntervalSince1970,
"level": level.rawValue,
"message": msg,
"thread": thread,
"fileName": file.components(separatedBy: "/").last!,
"function": function,
"line": line]
jsonString = jsonStringFromDict(dict)
if let str = jsonString {
toNSLog("saving '\(msg)' to \(entriesFileURL)")
let _ = saveToFile(str, url: entriesFileURL)
//toNSLog(entriesFileURL.path!)
// now decide if the stored log entries should be sent to the server
// add level points to current points amount and send to server if threshold is hit
let newPoints = sendingPointsForLevel(level)
points += newPoints
toNSLog("current sending points: \(points)")
if (points >= sendingPoints.threshold && points >= minAllowedThreshold) || points > maxAllowedThreshold {
toNSLog("\(points) points is >= threshold")
// above threshold, send to server
sendNow()
} else if initialSending {
initialSending = false
// first logging at this session
// send if json file still contains old log entries
if let logEntries = logsFromFile(entriesFileURL) {
let lines = logEntries.count
if lines > 1 {
var msg = "initialSending: \(points) points is below threshold "
msg += "but json file already has \(lines) lines."
toNSLog(msg)
sendNow()
}
}
}
}
return jsonString
}
// MARK: Send-to-Server Logic
/// does a (manual) sending attempt of all unsent log entries to SwiftyBeaver Platform
public func sendNow() {
if sendFileExists() {
toNSLog("reset points to 0")
points = 0
} else {
if !renameJsonToSendFile() {
return
}
}
if !sendingInProgress {
sendingInProgress = true
//let (jsonString, lines) = logsFromFile(sendingFileURL)
var lines = 0
guard let logEntries = logsFromFile(sendingFileURL) else {
sendingInProgress = false
return
}
lines = logEntries.count
if lines > 0 {
var payload = [String: Any]()
// merge device and analytics dictionaries
let deviceDetailsDict = deviceDetails()
var analyticsDict = analytics(analyticsFileURL)
for key in deviceDetailsDict.keys {
analyticsDict[key] = deviceDetailsDict[key]
}
payload["device"] = analyticsDict
payload["entries"] = logEntries
if let str = jsonStringFromDict(payload) {
//toNSLog(str) // uncomment to see full payload
toNSLog("Encrypting \(lines) log entries ...")
if let encryptedStr = encrypt(str) {
var msg = "Sending \(lines) encrypted log entries "
msg += "(\(encryptedStr.characters.count) chars) to server ..."
toNSLog(msg)
//toNSLog("Sending \(encryptedStr) ...")
sendToServerAsync(encryptedStr) { ok, _ in
self.toNSLog("Sent \(lines) encrypted log entries to server, received ok: \(ok)")
if ok {
let _ = self.deleteFile(self.sendingFileURL)
}
self.sendingInProgress = false
self.points = 0
}
}
}
} else {
sendingInProgress = false
}
}
}
/// sends a string to the SwiftyBeaver Platform server, returns ok if status 200 and HTTP status
func sendToServerAsync(_ str: String?, complete: @escaping (_ ok: Bool, _ status: Int) -> Void) {
let timeout = 10.0
if let payload = str, let queue = self.queue, let serverURL = serverURL {
// create operation queue which uses current serial queue of destination
let operationQueue = OperationQueue()
operationQueue.underlyingQueue = queue
let session = URLSession(configuration:
URLSessionConfiguration.default,
delegate: nil, delegateQueue: operationQueue)
toNSLog("assembling request ...")
// assemble request
var request = URLRequest(url: serverURL,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: timeout)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// basic auth header (just works on Linux for Swift 3.1+, macOS is fine)
guard let credentials = "\(appID):\(appSecret)".data(using: String.Encoding.utf8) else {
toNSLog("Error! Could not set basic auth header")
return complete(false, 0)
}
let base64Credentials = credentials.base64EncodedString(options: [])
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
//toNSLog("\nrequest:")
//print(request)
// POST parameters
let params = ["payload": payload]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
} catch {
toNSLog("Error! Could not create JSON for server payload.")
return complete(false, 0)
}
toNSLog("sending params: \(params)")
toNSLog("sending ...")
sendingInProgress = true
// send request async to server on destination queue
let task = session.dataTask(with: request) { _, response, error in
var ok = false
var status = 0
self.toNSLog("received response from server")
if let error = error {
// an error did occur
self.toNSLog("Error! Could not send entries to server. \(error)")
} else {
if let response = response as? HTTPURLResponse {
status = response.statusCode
if status == 200 {
// all went well, entries were uploaded to server
ok = true
} else {
// status code was not 200
var msg = "Error! Sending entries to server failed "
msg += "with status code \(status)"
self.toNSLog(msg)
}
}
}
return complete(ok, status)
}
task.resume()
//while true {} // commenting this line causes a crash on Linux unit tests?!?
}
}
/// returns sending points based on level
func sendingPointsForLevel(_ level: SwiftyBeaver.Level) -> Int {
switch level {
case SwiftyBeaver.Level.debug:
return sendingPoints.debug
case SwiftyBeaver.Level.info:
return sendingPoints.info
case SwiftyBeaver.Level.warning:
return sendingPoints.warning
case SwiftyBeaver.Level.error:
return sendingPoints.error
default:
return sendingPoints.verbose
}
}
// MARK: File Handling
/// appends a string as line to a file.
/// returns boolean about success
func saveToFile(_ str: String, url: URL, overwrite: Bool = false) -> Bool {
do {
if fileManager.fileExists(atPath: url.path) == false || overwrite {
// create file if not existing
let line = str + "\n"
try line.write(to: url, atomically: true, encoding: String.Encoding.utf8)
} else {
// append to end of file
let fileHandle = try FileHandle(forWritingTo: url)
let _ = fileHandle.seekToEndOfFile()
let line = str + "\n"
if let data = line.data(using: String.Encoding.utf8) {
fileHandle.write(data)
fileHandle.closeFile()
}
}
return true
} catch {
toNSLog("Error! Could not write to file \(url).")
return false
}
}
func sendFileExists() -> Bool {
return fileManager.fileExists(atPath: sendingFileURL.path)
}
func renameJsonToSendFile() -> Bool {
do {
try fileManager.moveItem(at: entriesFileURL, to: sendingFileURL)
return true
} catch {
toNSLog("SwiftyBeaver Platform Destination could not rename json file.")
return false
}
}
/// returns optional array of log dicts from a file which has 1 json string per line
func logsFromFile(_ url: URL) -> [[String:Any]]? {
var lines = 0
do {
// try to read file, decode every JSON line and put dict from each line in array
let fileContent = try String(contentsOfFile: url.path, encoding: .utf8)
let linesArray = fileContent.components(separatedBy: "\n")
var dicts = [[String: Any]()] // array of dictionaries
for lineJSON in linesArray {
lines += 1
if lineJSON.characters.first == "{" && lineJSON.characters.last == "}" {
// try to parse json string into dict
if let data = lineJSON.data(using: .utf8) {
do {
if let dict = try JSONSerialization.jsonObject(with: data,
options: .mutableContainers) as? [String:Any] {
if !dict.isEmpty {
dicts.append(dict)
}
}
} catch {
var msg = "Error! Could not parse "
msg += "line \(lines) in file \(url)."
toNSLog(msg)
}
}
}
}
dicts.removeFirst()
return dicts
} catch {
toNSLog("Error! Could not read file \(url).")
}
return nil
}
/// returns AES-256 CBC encrypted optional string
func encrypt(_ str: String) -> String? {
return AES256CBC.encryptString(str, password: encryptionKey)
}
/// Delete file to get started again
func deleteFile(_ url: URL) -> Bool {
do {
try FileManager.default.removeItem(at: url)
return true
} catch {
toNSLog("Warning! Could not delete file \(url).")
}
return false
}
// MARK: Device & Analytics
// returns dict with device details. Amount depends on platform
func deviceDetails() -> [String: String] {
var details = [String: String]()
details["os"] = OS
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
// becomes for example 10.11.2 for El Capitan
var osVersionStr = String(osVersion.majorVersion)
osVersionStr += "." + String(osVersion.minorVersion)
osVersionStr += "." + String(osVersion.patchVersion)
details["osVersion"] = osVersionStr
details["hostName"] = ProcessInfo.processInfo.hostName
details["deviceName"] = ""
details["deviceModel"] = ""
if DEVICE_NAME != "" {
details["deviceName"] = DEVICE_NAME
}
if DEVICE_MODEL != "" {
details["deviceModel"] = DEVICE_MODEL
}
return details
}
/// returns (updated) analytics dict, optionally loaded from file.
func analytics(_ url: URL, update: Bool = false) -> [String:Any] {
var dict = [String: Any]()
let now = NSDate().timeIntervalSince1970
uuid = NSUUID().uuidString
dict["uuid"] = uuid
dict["firstStart"] = now
dict["lastStart"] = now
dict["starts"] = 1
dict["userName"] = analyticsUserName
dict["firstAppVersion"] = appVersion()
dict["appVersion"] = appVersion()
dict["firstAppBuild"] = appBuild()
dict["appBuild"] = appBuild()
if let loadedDict = dictFromFile(analyticsFileURL) {
if let val = loadedDict["firstStart"] as? Double {
dict["firstStart"] = val
}
if let val = loadedDict["lastStart"] as? Double {
if update {
dict["lastStart"] = now
} else {
dict["lastStart"] = val
}
}
if let val = loadedDict["starts"] as? Int {
if update {
dict["starts"] = val + 1
} else {
dict["starts"] = val
}
}
if let val = loadedDict["uuid"] as? String {
dict["uuid"] = val
uuid = val
}
if let val = loadedDict["userName"] as? String {
if update && !analyticsUserName.isEmpty {
dict["userName"] = analyticsUserName
} else {
if !val.isEmpty {
dict["userName"] = val
}
}
}
if let val = loadedDict["firstAppVersion"] as? String {
dict["firstAppVersion"] = val
}
if let val = loadedDict["firstAppBuild"] as? Int {
dict["firstAppBuild"] = val
}
}
return dict
}
/// Returns the current app version string (like 1.2.5) or empty string on error
func appVersion() -> String {
if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
return version
}
return ""
}
/// Returns the current app build as integer (like 563, always incrementing) or 0 on error
func appBuild() -> Int {
if let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
if let intVersion = Int(version) {
return intVersion
}
}
return 0
}
/// returns optional dict from a json encoded file
func dictFromFile(_ url: URL) -> [String:Any]? {
do {
let fileContent = try String(contentsOfFile: url.path, encoding: .utf8)
if let data = fileContent.data(using: .utf8) {
return try JSONSerialization.jsonObject(with: data,
options: .mutableContainers) as? [String:Any]
}
} catch {
toNSLog("SwiftyBeaver Platform Destination could not read file \(url)")
}
return nil
}
// turns dict into JSON and saves it to file
func saveDictToFile(_ dict: [String: Any], url: URL) -> Bool {
let jsonString = jsonStringFromDict(dict)
if let str = jsonString {
toNSLog("saving '\(str)' to \(url)")
return saveToFile(str, url: url, overwrite: true)
}
return false
}
// MARK: Debug Helpers
/// log String to toNSLog. Used to debug the class logic
func toNSLog(_ str: String) {
if showNSLog {
#if os(Linux)
print("SBPlatform: \(str)")
#else
NSLog("SBPlatform: \(str)")
#endif
}
}
/// returns the current thread name
class func threadName() -> String {
#if os(Linux)
// on 9/30/2016 not yet implemented in server-side Swift:
// > import Foundation
// > Thread.isMainThread
return ""
#else
if Thread.isMainThread {
return ""
} else {
let threadName = Thread.current.name
if let threadName = threadName, !threadName.isEmpty {
return threadName
} else {
return String(format: "%p", Thread.current)
}
}
#endif
}
}
| mit | 11fb8c82328bc111618e9afecf20e88a | 37.134959 | 117 | 0.527651 | 5.41015 | false | false | false | false |
informmegp2/inform-me | InformME/ProfileViewController.swift | 1 | 7044 | //
// ProfileViewController.swift
// InformME
//
// Created by Amal Ibrahim on 2/5/16.
// Copyright © 2016 King Saud University. All rights reserved.
//backtohoempage
import Foundation
import UIKit
class ProfileViewController: CenterViewController , UITextFieldDelegate{
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet var usernameFiled: UITextField!
@IBOutlet var emailFiled: UITextField!
@IBOutlet var bioFiled: UITextField!
@IBOutlet var passwordFiled: UITextField!
var e: Attendee = Attendee()
/*Hello : ) */
override func viewDidLoad() {
super.viewDidLoad()
usernameFiled.delegate = self
emailFiled.delegate = self
bioFiled.delegate = self
passwordFiled.delegate = self
if(Reachability.isConnectedToNetwork()){
e.requestInfo(){
(AttendeeInfo:Attendee) in
dispatch_async(dispatch_get_main_queue()) {
self.usernameFiled.text = AttendeeInfo.username
self.emailFiled.text = AttendeeInfo.email
self.bioFiled.text = AttendeeInfo.bio
}
}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
@IBAction func save(sender: AnyObject) {
let username = usernameFiled.text!
let email = emailFiled.text!
let password = passwordFiled.text!
let bio = bioFiled.text!
var count: Int
count = password.characters.count
if (username.isEmpty || email.isEmpty || password.isEmpty) {
displayAlert("", message: "يرجى إدخال كافة الحقول")
}// end if chack
else if ( count < 8)
{
displayAlert("", message: "يرجى إدخال كلمة مرور لا تقل عن ثمانية أحرف")
}//end else if
else if (isValidEmail(email) == false) {
displayAlert("", message: " يرجى إدخال صيغة بريد الكتروني صحيحة")
}
else {
let alertController = UIAlertController(title: "", message: " هل أنت متأكد من رغبتك بحفظ التغييرات؟", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "موافق", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
let e : Attendee = Attendee()
if(Reachability.isConnectedToNetwork()){
e.UpdateProfile ( username, email: email, password: password, bio: bio){
(flag:Bool) in
if(flag) {
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
print("Heeeeello")
self.performSegueWithIdentifier("backtohoempage", sender:sender)
}}
else{
self.displayAlert("", message: "البريد الإلكتروني مسجل لدينا سابقاً")
}
}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
let cancelAction = UIAlertAction(title: "إلغاء الأمر", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
NSLog("Cancel Pressed")
}
//Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
}
}// end fun save
//for alert massge
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
if( message != "يرجى إدخال كافة الحقول") {
self.dismissViewControllerAnimated(true, completion: nil) }
})))
self.presentViewController(alert, animated: true, completion: nil)
}//end fun display alert
// *** for keyboard
@IBOutlet var scrollView: UIScrollView!
func textFieldDidBeginEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 150)), animated: true)
}
func textFieldDidEndEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 0)), animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// *** for keyboard
var window:UIWindow!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
if(segue.identifier == "backtohoempage"){
containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("CenterViewController2") as? CenterViewController
print(window!.rootViewController)
window!.rootViewController = containerViewController
print(window!.rootViewController)
window!.makeKeyAndVisible()
containerViewController.centerViewController.delegate?.collapseSidePanels!()
}
}
func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) }
}
| mit | 5e9d44fb25ce5e0ef70d667f7c64612e | 29.837104 | 165 | 0.549963 | 5.055638 | false | false | false | false |
335g/TwitterAPIKit | Sources/APIs/DirectMessagesAPI.swift | 1 | 5188 | //
// DirectMessages.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/05.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
import APIKit
// MARK: - Request
public protocol DirectMessagesRequestType: TwitterAPIRequestType {}
public protocol DirectMessagesGetRequestType: DirectMessagesRequestType {}
public protocol DirectMessagesPostRequestType: DirectMessagesRequestType {}
public extension DirectMessagesRequestType {
public var baseURL: NSURL {
return NSURL(string: "https://api.twitter.com/1.1")!
}
}
public extension DirectMessagesGetRequestType {
public var method: APIKit.HTTPMethod {
return .GET
}
}
public extension DirectMessagesPostRequestType {
public var method: APIKit.HTTPMethod {
return .POST
}
}
// MARK: - API
public enum TwitterDirectMessages {
///
/// https://dev.twitter.com/rest/reference/get/direct_messages/sent
///
public struct Sent: DirectMessagesGetRequestType, MultipleDirectMessagesResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/direct_messages/sent.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
count: Int = 50,
page: Int? = nil,
includeEntities: Bool = false){
self.client = client
self._parameters = [
"since_id": sinceIDStr,
"max_id": maxIDStr,
"count": count,
"page": page,
"include_entities": includeEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [DirectMessage] {
return try directMessagesFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/direct_messages/show
///
public struct Show: DirectMessagesGetRequestType, MultipleDirectMessagesResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/direct_messages/show.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String){
self.client = client
self._parameters = ["id": idStr]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [DirectMessage] {
return try directMessagesFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/direct_messages
///
public struct Received: DirectMessagesGetRequestType, MultipleDirectMessagesResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/direct_messages.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
count: Int = 50,
includeEntities: Bool = false,
skipStatus: Bool = true){
self.client = client
self._parameters = [
"since_id": sinceIDStr,
"max_id": maxIDStr,
"count": count,
"include_entities": includeEntities,
"skip_status": skipStatus
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [DirectMessage] {
return try directMessagesFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/direct_messages/destroy
///
public struct Destroy: DirectMessagesPostRequestType, SingleDirectMessageResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/direct_messages/destroy.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
includeEntities: Bool = false){
self.client = client
self._parameters = [
"id": idStr,
"include_entities": includeEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> DirectMessage {
return try directMessageFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/direct_messages/new
///
public struct New: DirectMessagesPostRequestType, SingleDirectMessageResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/direct_messages/new.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User,
text: String){
self.client = client
self._parameters = [
user.key: user.obj,
"text": text
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> DirectMessage {
return try directMessageFromObject(object, URLResponse)
}
}
}
| mit | 03d3ba1dc160b1b4280f3b4d826c1cee | 24.048309 | 111 | 0.706075 | 3.880988 | false | false | false | false |
adrfer/swift | test/SIL/whole_module_optimization.swift | 20 | 1569 | // RUN: %target-swift-frontend -emit-sil -O %s %S/Inputs/whole_module_optimization_helper.swift -o %t.sil -module-name main
// RUN: FileCheck %s < %t.sil
// RUN: FileCheck %s -check-prefix=NEGATIVE < %t.sil
// RUN: %target-swift-frontend -emit-sil -O -primary-file %s %S/Inputs/whole_module_optimization_helper.swift -o %t.unopt.sil -module-name main
// RUN: FileCheck %s -check-prefix=CHECK-SINGLE-FILE < %t.unopt.sil
// RUN: %target-swift-frontend -emit-sil -O -enable-testing %s %S/Inputs/whole_module_optimization_helper.swift -o %t.testing.sil -module-name main
// RUN: FileCheck %s < %t.testing.sil
// RUN: FileCheck %s -check-prefix=NEGATIVE-TESTABLE < %t.testing.sil
private func privateFn() -> Int32 {
return 2
}
// CHECK-LABEL: sil @_TF4main9getAnswerFT_Vs5Int32
// CHECK-SINGLE-FILE-LABEL: sil @_TF4main9getAnswerFT_Vs5Int32
public func getAnswer() -> Int32 {
// CHECK: %0 = integer_literal $Builtin.Int32, 42
// CHECK-NEXT: %1 = struct $Int32 (%0 : $Builtin.Int32)
// CHECK-NEXT: return %1 : $Int32
// CHECK-SINGLE-FILE: %0 = function_ref @_TF4main7computeFFT_Vs5Int32S0_
// CHECK-SINGLE-FILE: %1 = function_ref @_TF4mainP33_4704C82F83811927370AA02DFDC75B5A9privateFnFT_Vs5Int32
// CHECK-SINGLE-FILE: %2 = thin_to_thick_function %1
// CHECK-SINGLE-FILE: %3 = apply %0(%2)
// CHECK-SINGLE-FILE: return %3 : $Int
return compute(privateFn)
}
// CHECK: }
// CHECK-SINGLE-FILE: }
// NEGATIVE-NOT: sil {{.+}}privateFn
// NEGATIVE-TESTABLE-NOT: sil {{.+}}privateFn
// NEGATIVE-NOT: sil {{.+}}compute
// CHECK-TESTABLE: sil {{.+}}compute
| apache-2.0 | 79dd2a4da0e5edb845ee81eda94ba6f2 | 41.405405 | 147 | 0.693435 | 2.868373 | false | true | false | false |
AbdullahBayraktar/restaurants-app | RestaurantsApp/RestaurantsApp/Features/RetaurantsList/ViewModels/RestaurantCellViewModel.swift | 1 | 2833 | //
// RestaurantCellViewModel.swift
// RestaurantsApp
//
// Created by Abdullah Bayraktar on 27/09/2017.
// Copyright © 2017 AB. All rights reserved.
//
import Foundation
import UIKit
class RestaurantCellViewModel: NSObject {
//MARK: Properties
let restaurant: Restaurant
let selectedSortOption: SortOptions
//MARK: Lifecycle
/**
Initializes view model with restaurant object.
- Parameter restaurant: Restaurant Data Model.
*/
init(restaurant: Restaurant, selectedSortOption: SortOptions) {
self.restaurant = restaurant
self.selectedSortOption = selectedSortOption
}
func getSortValue() -> String {
var sortValueString = selectedSortOption.rawValue + ": "
switch selectedSortOption {
case .bestMatch:
sortValueString += "\(restaurant.bestMatch)"
case .newest:
sortValueString += "\(restaurant.newest)"
case .ratingAverage:
sortValueString += "\(restaurant.ratingAverage)"
case .distance:
sortValueString += "\(restaurant.distance)"
case .popularity:
sortValueString += "\(restaurant.popularity)"
case .averageProductPrice:
sortValueString += "\(restaurant.averageProductPrice)"
case .deliveryCosts:
sortValueString += "\(restaurant.deliveryCosts)"
case .minimumCost:
sortValueString += "\(restaurant.minimumCost)"
}
return sortValueString
}
func getFavoriteStatus() -> Bool {
return restaurant.favoriteStatus()
}
}
//MARK: CellRepresentable
extension RestaurantCellViewModel: CellRepresentable {
/**
Registers a nib for table view cell
*/
static func registerCell(tableView: UITableView) {
let cellNib = UINib(nibName: RestaurantsTableViewCell.className, bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: RestaurantsTableViewCell.className)
}
/**
Dequeues an already allocated cell or allocates a new one.
- Returns: Table View Cell Instance.
*/
func dequeueCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell: RestaurantsTableViewCell = tableView.dequeueReusableCell(withIdentifier: RestaurantsTableViewCell.className) as! RestaurantsTableViewCell!
cell.setupLogic(with: restaurant, sortValue: getSortValue(), favoriteState: getFavoriteStatus())
cell.tag = indexPath.row
return cell
}
/**
Gets Data Model for the selected cell.
- Returns: Data Model object of Any type.
*/
func modelForSelectedCell() -> Any {
return restaurant
}
}
| mit | d1446c95811dae6e0d005c9408760be0 | 27.32 | 156 | 0.63524 | 5.254174 | false | false | false | false |
tadasz/MistikA | MistikA/Classes/StarEmitterView.swift | 1 | 3173 | //
// StarEmitterView.swift
// MistikA
//
// Created by Tadas Ziemys on 11/07/14.
// Copyright (c) 2014 Tadas Ziemys. All rights reserved.
//
import UIKit
import QuartzCore
class StarEmitterView: UIView {
var starsEmitter: CAEmitterLayer?
override func awakeFromNib() {
starsEmitter = CAEmitterLayer()
if starsEmitter != nil {
//configure the emitter layer
starsEmitter!.emitterPosition = CGPointMake(160, 240);
starsEmitter!.emitterSize = CGSizeMake(self.superview!.bounds.size.width,self.superview!.bounds.size.height);
starsEmitter!.renderMode = kCAEmitterLayerPoints;
starsEmitter!.emitterShape = kCAEmitterLayerRectangle;
starsEmitter!.emitterMode = kCAEmitterLayerUnordered;
let stars = CAEmitterCell()
stars.birthRate = 2
stars.lifetime = 10
stars.lifetimeRange = 0.5
stars.color = UIColor.whiteColor().CGColor
stars.contents = UIImage(named: "particle.png")!.CGImage
stars.velocityRange = 300
stars.emissionRange = 360
stars.scale = 0.2
stars.scaleRange = 0.1
stars.alphaRange = 0.1
stars.alphaSpeed = 0.6
stars.name = "stars"
//add the cell to the layer and we're done
starsEmitter!.emitterCells = [stars];
layer.addSublayer(starsEmitter!)
}
}
func layerClass() -> AnyClass {
return CAEmitterLayer.classForCoder()
}
}
/*
@implementation Emitter
{
CAEmitterLayer* starsEmitter; //1
}
-(void)awakeFromNib
{
//set ref to the layer
starsEmitter = (CAEmitterLayer*)self.layer; //2
//configure the emitter layer
starsEmitter.emitterPosition = CGPointMake(160, 240);
starsEmitter.emitterSize = CGSizeMake(self.superview.bounds.size.width,self.superview.bounds.size.height);
NSLog(@"width = %f, height = %f", starsEmitter.emitterSize.width, starsEmitter.emitterSize.height);
starsEmitter.renderMode = kCAEmitterLayerPoints;
starsEmitter.emitterShape = kCAEmitterLayerRectangle;
starsEmitter.emitterMode = kCAEmitterLayerUnordered;
CAEmitterCell* stars = [CAEmitterCell emitterCell];
stars.birthRate = 0;
stars.lifetime = 10;
stars.lifetimeRange = 0.5;
stars.color = [[UIColor colorWithRed:255 green:255 blue:255 alpha:0]
CGColor];
stars.contents = (id)[[UIImage imageNamed:@"particle.png"] CGImage];
stars.velocityRange = 500;
stars.emissionRange = 360;
stars.scale = 0.2;
stars.scaleRange = 0.1;
stars.alphaRange = 0.3;
stars.alphaSpeed = 0.5;
[stars setName:@"stars"];
//add the cell to the layer and we're done
starsEmitter.emitterCells = [NSArray arrayWithObject:stars];
}
+ (Class) layerClass //3
{
//configure the UIView to have emitter layer
return [CAEmitterLayer class];
}
-(void)setIsEmitting:(BOOL)isEmitting
{
//turn on/off the emitting of particles
[starsEmitter setValue:[NSNumber numberWithInt:isEmitting?2:0]
forKeyPath:@"emitterCells.stars.birthRate"];
}
-(void)stopAnimations {
[starsEmitter removeAllAnimations];
}
*/ | mit | 8254966ba5b65ee7d2fa53fa1590104c | 26.128205 | 121 | 0.668768 | 4.202649 | false | false | false | false |
tomtclai/swift-algorithm-club | Union-Find/UnionFind.playground/Sources/UnionFindQuickFind.swift | 8 | 1325 | import Foundation
/// Quick-find algorithm may take ~MN steps
/// to process M union commands on N objects
public struct UnionFindQuickFind<T: Hashable> {
private var index = [T: Int]()
private var parent = [Int]()
private var size = [Int]()
public init() {}
public mutating func addSetWith(_ element: T) {
index[element] = parent.count
parent.append(parent.count)
size.append(1)
}
private mutating func setByIndex(_ index: Int) -> Int {
return parent[index]
}
public mutating func setOf(_ element: T) -> Int? {
if let indexOfElement = index[element] {
return setByIndex(indexOfElement)
} else {
return nil
}
}
public mutating func unionSetsContaining(_ firstElement: T, and secondElement: T) {
if let firstSet = setOf(firstElement), let secondSet = setOf(secondElement) {
if firstSet != secondSet {
for index in 0..<parent.count {
if parent[index] == firstSet {
parent[index] = secondSet
}
}
size[secondSet] += size[firstSet]
}
}
}
public mutating func inSameSet(_ firstElement: T, and secondElement: T) -> Bool {
if let firstSet = setOf(firstElement), let secondSet = setOf(secondElement) {
return firstSet == secondSet
} else {
return false
}
}
}
| mit | b6e596411a52851bcfbc2c692bb8e9c4 | 25.5 | 85 | 0.630943 | 4.206349 | false | false | false | false |
IcyButterfly/ListDataProvider | ListDataProvider/ListDataProvider/PagedListDataProvider.swift | 1 | 2605 | //
// PagedListDataProvider.swift
// ListDataProvider
//
// Created by ET|冰琳 on 2017/3/10.
// Copyright © 2017年 UK. All rights reserved.
//
import Foundation
public protocol PagedListDataProvider: ListDataProvider {
func isEmpty() -> Bool
var hasMore: Bool { get set }
}
struct PagedListDataProviderDefault {
static var pageIndex: Int = 1
static var pageSize: Int = 10
}
extension PagedListDataProvider where Self: ArrayContainer{
public func isEmpty() -> Bool {
return self.items.count == 0
}
/// 计算页码
///
/// - Parameters:
/// - count: 每页个数
/// - more: 是否是加载更多
/// - startIndex: 起始页码的数量 默认值为1
/// - Returns: more true: 加载更多的页数
/// false: 刷新时的页数
public func pageIndex(withPageCount count: Int = PagedListDataProviderDefault.pageSize,
isRequestMore more: Bool,
startIndex: Int = PagedListDataProviderDefault.pageIndex) -> Int{
if more == false{
return startIndex
}
let total = self.items.count
return Int( ceil( Double(total) / Double(count))) + startIndex
}
/// 通过接口返回的数据的数量判断是否还有更多
///
/// eg: pageCount为10
/// contentsOf的count为1 则可以判断没有更多了
/// contentsOf的count为10 则可能是还有更多 也可能是没有更多了,此时 本方法判断结果为还有更多
/// 此时如果服务器并未给出是否还有更多的字段,则可以通过再获取一页来判断,直到获取到的数量小于10 就没有更多了
public func append(contentsOf: [Data],
isRequestMore more: Bool,
pageCount: Int = PagedListDataProviderDefault.pageSize) {
if more == false {
self.items.removeAll()
}
self.items.append(contentsOf: contentsOf)
if contentsOf.count < pageCount {
self.hasMore = false
}else{
self.hasMore = true
}
}
/// 接口有返回的是否还有更多
///
/// - Parameters:
/// - hasMore: API返回的是否还有更多
public func append(contentsOf: [Data], isRequestMore more: Bool, hasMore: Bool) {
if more == false {
self.items.removeAll()
}
self.items.append(contentsOf: contentsOf)
self.hasMore = hasMore
}
}
| mit | b068944f5314bc0261b671c7ac57e6e3 | 26.036145 | 91 | 0.569073 | 4.140221 | false | false | false | false |
programming086/ios-charts | Charts/Classes/Charts/BarLineChartViewBase.swift | 1 | 64795 | //
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _autoScaleLastLowestVisibleXIndex: Int!
private var _autoScaleLastHighestVisibleXIndex: Int!
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// Sets the minimum offset (padding) around the chart, defaults to 10
public var minOffset = CGFloat(10.0)
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
internal var _tapGestureRecognizer: UITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: UITapGestureRecognizer!
#if !os(tvOS)
internal var _pinchGestureRecognizer: UIPinchGestureRecognizer!
#endif
internal var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxis = ChartYAxis(position: .Left)
_rightAxis = ChartYAxis(position: .Right)
_xAxis = ChartXAxis()
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
_highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"))
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"))
_doubleTapGestureRecognizer.numberOfTapsRequired = 2
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"))
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
_panGestureRecognizer.enabled = _dragEnabled
#if !os(tvOS)
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"))
_pinchGestureRecognizer.delegate = self
self.addGestureRecognizer(_pinchGestureRecognizer)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let optionalContext = UIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
calcModulus()
if (_xAxisRenderer !== nil)
{
_xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
if (renderer !== nil)
{
renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
// execute all drawing commands
drawGridBackground(context: context)
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
}
_xAxisRenderer?.renderAxisLine(context: context)
_leftYAxisRenderer?.renderAxisLine(context: context)
_rightYAxisRenderer?.renderAxisLine(context: context)
if (_autoScaleMinMaxEnabled)
{
let lowestVisibleXIndex = self.lowestVisibleXIndex,
highestVisibleXIndex = self.highestVisibleXIndex
if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex ||
_autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex)
{
calcMinMax()
calculateOffsets()
_autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex
_autoScaleLastHighestVisibleXIndex = highestVisibleXIndex
}
}
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context)
CGContextClipToRect(context, _viewPortHandler.contentRect)
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
_xAxisRenderer?.renderGridLines(context: context)
_leftYAxisRenderer?.renderGridLines(context: context)
_rightYAxisRenderer?.renderGridLines(context: context)
renderer?.drawData(context: context)
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
// if highlighting is enabled
if (valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHighlight)
}
// Removes clipping rectangle
CGContextRestoreGState(context)
renderer!.drawExtras(context: context)
_xAxisRenderer.renderAxisLabels(context: context)
_leftYAxisRenderer.renderAxisLabels(context: context)
_rightYAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
// drawLegend()
drawMarkers(context: context)
drawDescription(context: context)
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted)
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return
}
calcMinMax()
_leftAxis?._defaultValueFormatter = _defaultValueFormatter
_rightAxis?._defaultValueFormatter = _defaultValueFormatter
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals)
if (_legend !== nil)
{
_legendRenderer?.computeLegend(_data)
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
if (_autoScaleMinMaxEnabled)
{
_data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex)
}
var minLeft = _data.getYMin(.Left)
var maxLeft = _data.getYMax(.Left)
var minRight = _data.getYMin(.Right)
var maxRight = _data.getYMax(.Right)
let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft))
let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight))
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0
}
}
let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop)
let topSpaceRight = rightRange * Double(_rightAxis.spaceTop)
let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom)
let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom)
_chartXMax = Double(_data.xVals.count - 1)
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
// Consider sticking one of the edges of the axis to zero (0.0)
if _leftAxis.isStartAtZeroEnabled
{
if minLeft < 0.0 && maxLeft < 0.0
{
// If the values are all negative, let's stay in the negative zone
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = 0.0
}
else if minLeft >= 0.0
{
// We have positive values only, stay in the positive zone
_leftAxis.axisMinimum = 0.0
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
}
else
{
// Use the values as they are
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)
}
if _rightAxis.isStartAtZeroEnabled
{
if minRight < 0.0 && maxRight < 0.0
{
// If the values are all negative, let's stay in the negative zone
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = 0.0
}
else if minRight >= 0.0
{
// We have positive values only, stay in the positive zone
_rightAxis.axisMinimum = 0.0
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
}
else
{
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum)
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum)
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
else if (_legend.position == .AboveChartLeft
|| _legend.position == .AboveChartRight
|| _legend.position == .AboveChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width
}
if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled)
{
let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil || !_xAxis.isEnabled)
{
return
}
if (!_xAxis.isAxisModulusCustom)
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelRotatedWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)))
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1
}
}
public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let dataSetIndex = highlight.dataSetIndex
var xPos = CGFloat(e.xIndex)
var yPos = CGFloat(e.value)
if (self.isKindOfClass(BarChartView))
{
let bd = _data as! BarChartData
let space = bd.groupSpace
let setCount = _data.dataSetCount
let i = e.xIndex
if self is HorizontalBarChartView
{
// calculate the x-position, depending on datasetcount
let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0
yPos = y
if let entry = e as? BarChartDataEntry
{
if entry.values != nil && highlight.range !== nil
{
xPos = CGFloat(highlight.range!.to)
}
else
{
xPos = CGFloat(e.value)
}
}
}
else
{
let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0
xPos = x
if let entry = e as? BarChartDataEntry
{
if entry.values != nil && highlight.range !== nil
{
yPos = CGFloat(highlight.range!.to)
}
else
{
yPos = CGFloat(e.value)
}
}
}
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY)
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt)
return pt
}
/// draws the grid background
internal func drawGridBackground(context context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context)
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor)
CGContextFillRect(context, _viewPortHandler.contentRect)
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth)
CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
CGContextStrokeRect(context, _viewPortHandler.contentRect)
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context)
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.Both
private var _closestDataSetToTouch: ChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: UIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if !self.isHighLightPerTapEnabled { return }
let h = getHighlightByTouchPoint(recognizer.locationInView(self))
if (h === nil || h!.isEqual(self.lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true)
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y)
}
}
}
#if !os(tvOS)
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration()
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both
}
else
{
let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x)
let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y)
if (x > y)
{
_gestureScaleAxis = .X
}
else
{
_gestureScaleAxis = .Y
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended ||
recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
let isZoomingOut = (recognizer.scale < 1)
var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY
if (_isScaling)
{
canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .X);
canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y);
if canZoomMoreX || canZoomMoreY
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
let scaleX = canZoomMoreX ? recognizer.scale : 1.0
let scaleY = canZoomMoreY ? recognizer.scale : 1.0
var matrix = CGAffineTransformMakeTranslation(location.x, location.y)
matrix = CGAffineTransformScale(matrix, scaleX, scaleY)
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y)
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.scale = 1.0
}
}
}
#endif
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0)
{
stopDeceleration()
if _dataNotSet
{ // If we have no data, we have nothing to pan and no data to highlight
return;
}
// If drag is enabled and we are in a position where there's something to drag:
// * If we're zoomed in, then obviously we have something to drag.
// * If we have a drag offset - we always have something to drag
if self.isDragEnabled &&
(!self.hasNoDragOffset || !self.isFullyZoomedOut)
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self))
let translation = recognizer.translationInView(self)
let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0
// Check to see if user dragged at all and if so, can the chart be dragged by the given amount
if (didUserDrag && !performPanChange(translation: translation))
{
if (_outerScrollView !== nil)
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if (_outerScrollView !== nil)
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.scrollEnabled = false
}
}
_lastPanPoint = recognizer.translationInView(self)
}
else if self.isHighlightPerDragEnabled
{
// We will only handle highlights on UIGestureRecognizerState.Changed
_isDragging = false
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
let originalTranslation = recognizer.translationInView(self)
let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if (isHighlightPerDragEnabled)
{
let h = getHighlightByTouchPoint(recognizer.locationInView(self))
let lastHighlighted = self.lastHighlighted
if ((h === nil && lastHighlighted !== nil) ||
(h !== nil && lastHighlighted === nil) ||
(h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted)))
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled)
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocityInView(self)
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"))
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
_isDragging = false
}
if (_outerScrollView !== nil)
{
_outerScrollView?.scrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(var translation translation: CGPoint) -> Bool
{
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
let originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y)
matrix = CGAffineTransformConcat(originalMatrix, matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
let distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if (!performPanChange(translation: distance))
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001)
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool
{
if (!super.gestureRecognizerShouldBegin(gestureRecognizer))
{
return false
}
if (gestureRecognizer == _panGestureRecognizer)
{
if _dataNotSet || !_dragEnabled ||
(self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled)
{
return false
}
}
else
{
#if !os(tvOS)
if (gestureRecognizer == _pinchGestureRecognizer)
{
if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled))
{
return false
}
}
#endif
}
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
#if !os(tvOS)
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) ||
(gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true
}
#endif
if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && (
gestureRecognizer == _panGestureRecognizer
))
{
var scrollView = self.superview
while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView))
{
scrollView = scrollView?.superview
}
// If there is two scrollview together, we pick the superview of the inner scrollview.
// In the case of UITableViewWrepperView, the superview will be UITableView
if let superViewOfScrollView = scrollView?.superview where superViewOfScrollView.isKindOfClass(UIScrollView)
{
scrollView = superViewOfScrollView
}
var foundScrollView = scrollView as? UIScrollView
if (foundScrollView !== nil && !foundScrollView!.scrollEnabled)
{
foundScrollView = nil
}
var scrollViewPanGestureRecognizer: UIGestureRecognizer!
if (foundScrollView !== nil)
{
for scrollRecognizer in foundScrollView!.gestureRecognizers!
{
if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer))
{
scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer
break
}
}
}
if (otherGestureRecognizer === scrollViewPanGestureRecognizer)
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center. center.
public func zoomIn()
{
let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center. center.
public func zoomOut()
{
let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter x:
/// - parameter y:
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
let matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMaximum(maxXRange: CGFloat)
{
let xScale = _deltaX / maxXRange
_viewPortHandler.setMinimumScaleX(xScale)
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMinimum(minXRange: CGFloat)
{
let xScale = _deltaX / minXRange
_viewPortHandler.setMaximumScaleX(xScale)
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling
public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat)
{
let maxScale = _deltaX / minXRange
let minScale = _deltaX / maxXRange
_viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale)
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
let yScale = getDeltaY(axis) / maxYRange
_viewPortHandler.setMinimumScaleY(yScale)
}
/// Moves the left side of the current viewport to the specified x-index.
/// This also refreshes the chart by calling setNeedsDisplay().
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0)
getTransformer(.Left).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); })
}
}
/// Centers the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); })
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xIndex:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xIndex:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`.
public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// - returns: the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange)
}
else
{
return CGFloat(rightAxis.axisRange)
}
}
/// - returns: the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value))
getTransformer(axis).pointValueToPixel(&vals)
return vals
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
}
}
}
/// **default**: true
/// - returns: true if zooming via double-tap is enabled false if not.
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
public var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a `UIScrollView`
///
/// **default**: true
public var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// **default**: true
/// - returns: true if drawing the grid background is enabled, false if not.
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// **default**: false
/// - returns: true if drawing the borders rectangle is enabled, false if not.
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
{
if (_dataNotSet || _data === nil)
{
print("Can't select by touch. No data set.", terminator: "\n")
return nil
}
return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y))
}
/// - returns: the x and y values in the chart at the given touch point
/// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// `getPixelsForValues(...)`.
public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt)
return pt
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to `getValueByTouchPoint(...)`.
public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y))
getTransformer(axis).pointValueToPixel(&pt)
return pt
}
/// - returns: the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y
}
/// - returns: the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
let h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data!.getEntryForHighlight(h!)
}
return nil
}
/// - returns: the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet!
{
let h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleBubbleChartDataSet!
}
return nil
}
/// - returns: the current x-scale factor
public var scaleX: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// - returns: the current y-scale factor
public var scaleY: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// - returns: the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis
}
/// - returns: the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// - returns: the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis
}
else
{
return _rightAxis
}
}
/// - returns: the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
/// **default**: false
/// - returns: true if pinch-zoom is enabled, false if not
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// - returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartXAxisRenderer
/// - returns: The current set X axis renderer
public var xAxisRenderer: ChartXAxisRenderer
{
get { return _xAxisRenderer }
set { _xAxisRenderer = newValue }
}
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartYAxisRenderer
/// - returns: The current set left Y axis renderer
public var leftYAxisRenderer: ChartYAxisRenderer
{
get { return _leftYAxisRenderer }
set { _leftYAxisRenderer = newValue }
}
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of ChartYAxisRenderer
/// - returns: The current set right Y axis renderer
public var rightYAxisRenderer: ChartYAxisRenderer
{
get { return _rightYAxisRenderer }
set { _rightYAxisRenderer = newValue }
}
public override var chartYMax: Double
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum)
}
public override var chartYMin: Double
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum)
}
/// - returns: true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
public var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled; }
set { _autoScaleMinMaxEnabled = newValue; }
}
/// **default**: false
/// - returns: true if auto scaling on the y axis is enabled.
public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; }
/// Sets a minimum width to the specified y axis.
public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.minWidth = width
}
else
{
_rightAxis.minWidth = width
}
}
/// **default**: 0.0
/// - returns: the (custom) minimum width of the specified Y axis.
public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.minWidth
}
else
{
return _rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.maxWidth = width
}
else
{
_rightAxis.maxWidth = width
}
}
/// Zero (0.0) means there's no maximum width
///
/// **default**: 0.0 (no maximum specified)
/// - returns: the (custom) maximum width of the specified Y axis.
public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.maxWidth
}
else
{
return _rightAxis.maxWidth
}
}
/// - returns the width of the specified y axis.
public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.requiredSize().width
}
else
{
return _rightAxis.requiredSize().width
}
}
// MARK: - BarLineScatterCandleBubbleChartDataProvider
/// - returns: the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
/// the number of maximum visible drawn values on the chart
/// only active when `setDrawValues()` is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount
}
set
{
_maxVisibleValueCount = newValue
}
}
public func isInverted(axis: ChartYAxis.AxisDependency) -> Bool
{
return getAxis(axis).isInverted
}
/// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (pt.x <= 0.0) ? 0 : Int(round(pt.x + 1.0))
}
/// - returns: the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (_data != nil && Int(round(pt.x)) >= _data.xValCount) ? _data.xValCount - 1 : Int(round(pt.x))
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
internal override init()
{
}
internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, dataProvider: LineChartDataProvider) -> CGFloat
{
var fillMin = CGFloat(0.0)
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0
}
else
{
if let data = dataProvider.data
{
if !dataProvider.getAxis(dataSet.axisDependency).isStartAtZeroEnabled
{
var max: Double, min: Double
if (data.yMax > 0.0)
{
max = 0.0
}
else
{
max = dataProvider.chartYMax
}
if (data.yMin < 0.0)
{
min = 0.0
}
else
{
min = dataProvider.chartYMin
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max)
}
else
{
fillMin = 0.0
}
}
}
return fillMin
}
}
| apache-2.0 | 28417ab8f8482334b181e43af1682be1 | 35.504225 | 238 | 0.575801 | 5.659446 | false | false | false | false |
aschwaighofer/swift | stdlib/public/Darwin/os/os_signpost.swift | 2 | 4439 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import os
@_exported import os.signpost
@_implementationOnly import _SwiftOSOverlayShims
import os.log
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public func os_signpost(
_ type: OSSignpostType,
dso: UnsafeRawPointer = #dsohandle,
log: OSLog,
name: StaticString,
signpostID: OSSignpostID = .exclusive
) {
let hasValidID = signpostID != .invalid && signpostID != .null
guard log.signpostsEnabled && hasValidID else { return }
let ra = _swift_os_log_return_address()
name.withUTF8Buffer { (nameBuf: UnsafeBufferPointer<UInt8>) in
// Since dladdr is in libc, it is safe to unsafeBitCast
// the cstring argument type.
nameBuf.baseAddress!.withMemoryRebound(
to: CChar.self, capacity: nameBuf.count
) { nameStr in
_swift_os_signpost(dso, ra, log, type, nameStr, signpostID.rawValue)
}
}
}
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public func os_signpost(
_ type: OSSignpostType,
dso: UnsafeRawPointer = #dsohandle,
log: OSLog,
name: StaticString,
signpostID: OSSignpostID = .exclusive,
_ format: StaticString,
_ arguments: CVarArg...
) {
let hasValidID = signpostID != .invalid && signpostID != .null
guard log.signpostsEnabled && hasValidID else { return }
let ra = _swift_os_log_return_address()
name.withUTF8Buffer { (nameBuf: UnsafeBufferPointer<UInt8>) in
// Since dladdr is in libc, it is safe to unsafeBitCast
// the cstring argument type.
nameBuf.baseAddress!.withMemoryRebound(
to: CChar.self, capacity: nameBuf.count
) { nameStr in
format.withUTF8Buffer { (formatBuf: UnsafeBufferPointer<UInt8>) in
// Since dladdr is in libc, it is safe to unsafeBitCast
// the cstring argument type.
formatBuf.baseAddress!.withMemoryRebound(
to: CChar.self, capacity: formatBuf.count
) { formatStr in
withVaList(arguments) { valist in
_swift_os_signpost_with_format(dso, ra, log, type,
nameStr, signpostID.rawValue, formatStr, valist)
}
}
}
}
}
}
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
extension OSSignpostType {
public static let event = __OS_SIGNPOST_EVENT
public static let begin = __OS_SIGNPOST_INTERVAL_BEGIN
public static let end = __OS_SIGNPOST_INTERVAL_END
}
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public struct OSSignpostID {
public let rawValue: os_signpost_id_t
public static let exclusive = OSSignpostID(_swift_os_signpost_id_exclusive())
public static let invalid = OSSignpostID(_swift_os_signpost_id_invalid())
public static let null = OSSignpostID(_swift_os_signpost_id_null())
public init(log: OSLog) {
self.rawValue = __os_signpost_id_generate(log)
}
public init(log: OSLog, object: AnyObject) {
self.rawValue = __os_signpost_id_make_with_pointer(log,
UnsafeRawPointer(Unmanaged.passUnretained(object).toOpaque()))
}
public init(_ value: UInt64) {
self.rawValue = value
}
}
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
extension OSSignpostID : Comparable {
public static func < (a: OSSignpostID, b: OSSignpostID) -> Bool {
return a.rawValue < b.rawValue
}
public static func == (a: OSSignpostID, b: OSSignpostID) -> Bool {
return a.rawValue == b.rawValue
}
}
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
extension OSLog {
public struct Category {
public let rawValue: String
public static let pointsOfInterest =
Category(string: String(cString: _swift_os_signpost_points_of_interest()))
private init(string: String) {
self.rawValue = string
}
}
public convenience init(subsystem: String, category: Category) {
self.init(__subsystem: subsystem, category: category.rawValue)
}
public var signpostsEnabled: Bool {
return __os_signpost_enabled(self)
}
}
| apache-2.0 | 394508f3131755d8b64e3294d8c41338 | 32.37594 | 82 | 0.663438 | 3.686877 | false | false | false | false |
IsaScience/ListerAProductivityAppObj-CandSwift | original-src/ListerAProductivityAppObj-CandSwift/Swift/Common/CheckBoxLayer.swift | 1 | 3030 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A CALayer subclass that draws a check box within its layer. This is shared between ListerKit and ListerKitOSX to draw their respective CheckBox controls.
*/
import QuartzCore
class CheckBoxLayer: CALayer {
// MARK: Types
struct SharedColors {
static let defaultTintColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.5, 0.5, 0.5])
}
// MARK: Properties
var tintColor: CGColor = SharedColors.defaultTintColor {
didSet {
setNeedsDisplay()
}
}
var isChecked: Bool = false {
didSet {
setNeedsDisplay()
}
}
var strokeFactor: CGFloat = 0.07 {
didSet {
setNeedsDisplay()
}
}
var insetFactor: CGFloat = 0.17 {
didSet {
setNeedsDisplay()
}
}
var markInsetFactor: CGFloat = 0.34 {
didSet {
setNeedsDisplay()
}
}
// The method that does the heavy lifting of check box drawing code.
override func drawInContext(context: CGContext) {
super.drawInContext(context)
let size = min(bounds.width, bounds.height)
var transform = affineTransform()
var xTranslate: CGFloat = 0
var yTranslate: CGFloat = 0
if bounds.size.width < bounds.size.height {
yTranslate = (bounds.height - size) / 2.0
}
else {
xTranslate = (bounds.width - size) / 2.0
}
transform = CGAffineTransformTranslate(transform, xTranslate, yTranslate)
let strokeWidth: CGFloat = strokeFactor * size
let checkBoxInset: CGFloat = insetFactor * size
// Create the outer border for the check box.
let outerDimension: CGFloat = size - 2.0 * checkBoxInset
var checkBoxRect = CGRect(x: checkBoxInset, y: checkBoxInset, width: outerDimension, height: outerDimension)
checkBoxRect = CGRectApplyAffineTransform(checkBoxRect, transform)
// Make the desired width of the outer box.
CGContextSetLineWidth(context, strokeWidth)
// Set the tint color of the outer box.
CGContextSetStrokeColorWithColor(context, tintColor)
// Draw the outer box.
CGContextStrokeRect(context, checkBoxRect)
// Draw the inner box if it's checked.
if isChecked {
let markInset: CGFloat = markInsetFactor * size
let markDimension: CGFloat = size - 2.0 * markInset
var markRect = CGRect(x: markInset, y: markInset, width: markDimension, height: markDimension)
markRect = CGRectApplyAffineTransform(markRect, transform)
CGContextSetFillColorWithColor(context, tintColor)
CGContextFillRect(context, markRect)
}
}
}
| apache-2.0 | 2971213344ee00d0d20c8f29491cb9be | 29.28 | 169 | 0.600396 | 5.238754 | false | false | false | false |
937447974/YJCocoa | YJCocoa/Classes/AppFrameworks/Foundation/Safety/NSDictionary+YJSafety.swift | 1 | 5330 | //
// NSDictionary+YJSafety.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/5/8.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import Foundation
extension NSDictionary {
open func bool(forKey key: Any) -> Bool {
guard let obj = self.object(forKey: key) else {
return false
}
if obj is NSNumber {
return (obj as! NSNumber).boolValue
}
if obj is NSString {
return (obj as! NSString).boolValue
}
return false
}
open func integer(forKey key: Any) -> Int {
guard let obj = self.object(forKey: key) else {
return 0
}
if obj is NSNumber {
return (obj as! NSNumber).intValue
}
if obj is NSString {
return (obj as! NSString).integerValue
}
return 0
}
open func float(forKey key: Any) -> Float {
guard let obj = self.object(forKey: key) else {
return 0.0
}
if obj is NSNumber {
return (obj as! NSNumber).floatValue
}
if obj is NSString {
return (obj as! NSString).floatValue
}
return 0.0
}
open func string(forKey key: Any) -> String {
guard let obj = self.object(forKey: key) else {
return ""
}
if obj is NSNumber {
return (obj as! NSNumber).stringValue
}
if obj is NSString {
return obj as! String
}
return ""
}
open func set(forKey key: Any) -> NSSet {
guard let obj = self.object(forKey: key) else {
return NSSet()
}
if obj is NSSet {
return obj as! NSSet
}
return NSSet()
}
open func array(forKey key: Any) -> NSArray {
guard let obj = self.object(forKey: key) else {
return NSArray()
}
if obj is NSArray {
return obj as! NSArray
}
return NSArray()
}
open func dictionary(forKey key: Any) -> NSDictionary {
guard let obj = self.object(forKey: key) else {
return NSDictionary()
}
if obj is NSDictionary {
return obj as! NSDictionary
}
return NSDictionary()
}
}
extension NSMutableDictionary {
open func mutableSet(forKey key: Any) -> NSMutableSet {
var obj = self.object(forKey: key)
if obj is NSMutableSet {
return obj as! NSMutableSet
} else if obj is NSSet {
obj = (obj as! NSSet).mutableCopy()
} else {
obj = NSMutableSet()
}
self.setObject(obj!, forKey: key as! NSCopying)
return obj as! NSMutableSet
}
open func mutableArray(forKey key: Any) -> NSMutableArray {
var obj = self.object(forKey: key)
if obj is NSMutableArray {
return obj as! NSMutableArray
} else if obj is NSArray {
obj = (obj as! NSArray).mutableCopy()
} else {
obj = NSMutableArray()
}
self.setArray(obj!, forKey: key as! NSCopying)
return obj as! NSMutableArray
}
open func mutableDictionary(forKey key: Any) -> NSMutableDictionary {
var obj = self.object(forKey: key)
if obj is NSMutableDictionary {
return obj as! NSMutableDictionary
} else if obj is NSDictionary {
obj = (obj as! NSDictionary).mutableCopy()
} else {
obj = NSMutableDictionary()
}
self.setObject(obj!, forKey: key as! NSCopying)
return obj as! NSMutableDictionary
}
open func setBool(_ anObject: Bool, forKey aKey: NSCopying) {
self.setObject(anObject, forKey: aKey)
}
open func setInt(_ anObject: Int, forKey aKey: NSCopying) {
self.setObject(anObject, forKey: aKey)
}
open func setFloat(_ anObject: Float, forKey aKey: NSCopying) {
self.setObject(anObject, forKey: aKey)
}
open func setString(_ anObject: Any, forKey aKey: NSCopying) {
guard let obj = anObject as? NSString else {
YJLogError("[Dictionary] set key:\(aKey) 对应的 value:\(anObject) 错误")
return
}
self.setObject(obj, forKey: aKey)
}
open func setSet(_ anObject: Any, forKey aKey: NSCopying) {
guard let obj = anObject as? NSSet else {
YJLogError("[Dictionary] set key:\(aKey) 对应的 value:\(anObject) 错误")
return
}
self.setObject(obj, forKey: aKey)
}
open func setArray(_ anObject: Any, forKey aKey: NSCopying) {
guard let obj = anObject as? NSArray else {
YJLogError("[Dictionary] set key:\(aKey) 对应的 value:\(anObject) 错误")
return
}
self.setObject(obj, forKey: aKey)
}
open func setDictionary(_ anObject: Any, forKey aKey: NSCopying) {
guard let obj = anObject as? NSDictionary else {
YJLogError("[Dictionary] set key:\(aKey) 对应的 value:\(anObject) 错误")
return
}
self.setObject(obj, forKey: aKey)
}
}
| mit | d304442036bfed6f4b83fcc28d54e92b | 27.33871 | 79 | 0.546576 | 4.579496 | false | false | false | false |
TeletronicsDotAe/FloatingActionButton | Pod/Classes/FloatingActionButtonUtil.swift | 1 | 1461 | //
// FloatingActionButtonUtil.swift
// Adapted by Martin Jacon Rehder on 2016/04/17
//
// Original by
// Created by Takuma Yoshida on 2015/08/17.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
func withBezier(f: (UIBezierPath) -> ()) -> UIBezierPath {
let bezierPath = UIBezierPath()
f(bezierPath)
bezierPath.closePath()
return bezierPath
}
extension CALayer {
func appendShadow() {
shadowColor = UIColor.grayColor().CGColor
shadowRadius = 6.0
shadowOpacity = 0.7
shadowOffset = CGSize(width: 0, height: 4)
masksToBounds = false
}
func eraseShadow() {
shadowRadius = 0.0
shadowColor = UIColor.clearColor().CGColor
}
}
class CGMath {
static func radToDeg(rad: CGFloat) -> CGFloat {
return rad * 180 / CGFloat(M_PI)
}
static func degToRad(deg: CGFloat) -> CGFloat {
return deg * CGFloat(M_PI) / 180
}
static func circlePoint(center: CGPoint, radius: CGFloat, rad: CGFloat) -> CGPoint {
let x = center.x + radius * cos(rad)
let y = center.y + radius * sin(rad)
return CGPoint(x: x, y: y)
}
static func linSpace(from: CGFloat, to: CGFloat, n: Int) -> [CGFloat] {
var values: [CGFloat] = []
for i in 0..<n {
values.append((to - from) * CGFloat(i) / CGFloat(n - 1) + from)
}
return values
}
} | mit | b7be3b145e4ce958c99e16a7f436d52b | 24.614035 | 88 | 0.593557 | 3.859788 | false | false | false | false |
linchaosheng/CSSwiftWB | SwiftCSWB 3/SwiftCSWB/Class/Home/M/WBStatus.swift | 1 | 16909 | //
// WBStatus.swift
// SwiftCSWB
//
// Created by LCS on 16/5/4.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
import SDWebImage
import FMDB
// 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 WBStatus: NSObject{
var idstr : String?
// 重写时间的getter方法
var _created_at : String?
var created_at : String?{
set{
_created_at = newValue
}
get{
/**
1.今年
1> 今天
* 1分内: 刚刚
* 1分~59分内:xx分钟前
* 大于60分钟:xx小时前
2> 昨天
* 昨天 xx:xx
3> 其他
* xx-xx xx:xx
2.非今年
1> xxxx-xx-xx xx:xx
*/
// 设置日期格式(声明字符串里面每个数字和单词的含义)
// E:星期几
// M:月份
// d:几号(这个月的第几天)
// H:24小时制的小时
// m:分钟
// s:秒
// y:年
//_created_at = @"Tue Sep 30 17:06:25 +0600 2014";
let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
guard let createdAt = _created_at else {
return nil
}
let createdAtData : Date? = dateFormat.date(from: createdAt)
let nowDate = Date()
guard let createdDate = createdAtData else {
return nil
}
// 日历对象(方便比较两个日期之间的差距)
let calendar : Calendar = Calendar.current
// 计算两个日期之间的差值
let cmps : DateComponents = (calendar as NSCalendar).components([.year,.month,.day,.hour,.minute,.second], from: createdDate, to: nowDate, options: NSCalendar.Options(rawValue: 0))
if (createdDate.isThisYear()) { // 今年
if (createdDate.isYesterday()) { // 昨天
dateFormat.dateFormat = "昨天 HH:mm"
return dateFormat.string(from: createdDate)
} else if (createdDate.isToday()) { // 今天
if (cmps.hour! >= 1) {
return "\(cmps.hour)小时前"
} else if (cmps.minute! >= 1) {
return "\(cmps.minute)分钟前"
} else {
return "刚刚"
}
} else { // 今年的其他日子
dateFormat.dateFormat = "MM-dd HH:mm"
return dateFormat.string(from: createdDate)
}
} else { // 非今年
dateFormat.dateFormat = "yyyy-MM-dd HH:mm"
return dateFormat.string(from: createdDate)
}
return createdAt
}
}
var id : NSNumber?
// 重写来源的setter方法
var _source : String?
var source : String?{
/*
var str = "Hello, playground"
let i = str.index(str.startIndex, offsetBy: 7)
let j = str.index(str.endIndex, offsetBy: -6)
var subStr = str.substring(with: i..<j) // play
let start = str.range(of: " ")
let end = str.range(of: "g")
if let startRange = start, let endRange = end {
subStr = str.substring(with: startRange.upperBound..<endRange.lowerBound) // play
}
*/
set{
_source = newValue
// where 并且sourceStr 不等于 ""
if let sourceStr = _source, sourceStr != ""{
// 截取字符串 <a.........>ipone6s</a>
let start = sourceStr.range(of: ">")?.upperBound
let end = sourceStr.range(of: "</")?.lowerBound
if let startIndex = start, let endIndex = end {
_source = "来自: " + sourceStr.substring(with: startIndex..<endIndex)
}
}
}
get{
return _source
}
}
// 正文
var text : String?
// 转发微博模型
var forwordStatus : WBStatus?
// 微博配图大图数组
var _bmiddle_pic : [URL]?
var bmiddle_pic : [URL]?{
set{
_bmiddle_pic = newValue
}
get{
var pic_urls : [[String : AnyObject]]?
if (forwordStatus?.pic_urls != nil && forwordStatus?.pic_urls?.count != 0){
pic_urls = forwordStatus?.pic_urls
}else{
pic_urls = _pic_urls
}
_bmiddle_pic = [URL]()
// 处理大图数组
for dict in pic_urls!{
guard var urlStr = dict["thumbnail_pic"] as? String else{
continue
}
urlStr = urlStr.replacingOccurrences(of: "thumbnail", with: "bmiddle")
_bmiddle_pic?.append(URL(string: urlStr)!)
}
return _bmiddle_pic
}
}
// 微博配图(若有转发微博显示转发微博的图片,否则显示原创微博的图片)
var _pic_urls : [[String : AnyObject]]?
var pic_urls : [[String : AnyObject]]?{
set{
_pic_urls = newValue
}
get{
if (forwordStatus?.pic_urls != nil && forwordStatus?.pic_urls?.count != 0){
return forwordStatus?.pic_urls
}else{
return _pic_urls
}
}
}
// 用户模型
var user : WBUser?
// cell高度
var _cellHeight : CGFloat?
var cellHeight : CGFloat? {
get{
if _cellHeight == nil{
// 文字的最大尺寸
let maxSize = CGSize(width: UIScreen.main.bounds.width - CGFloat(2 * cellMargin), height: CGFloat(MAXFLOAT))
// 计算转发的高度
var forwordTextH : CGFloat = 0
if forwordStatus != nil {
if forwordStatus?.text != nil{
forwordTextH = ("@\(forwordStatus?.user?.screen_name):\(forwordStatus?.text)" as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17)], context: nil).size.height
}else{
forwordTextH = 0
}
}
// 计算文字的高度
var textH : CGFloat = 0
if text != nil{
textH = (text! as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17)], context: nil).size.height
}else{
textH = 0
}
if forwordStatus != nil {
_cellHeight = CGFloat(iconH) + CGFloat(5 * cellMargin) + textH + CGFloat(bottomBarH) + forwordTextH
}else{
_cellHeight = CGFloat(iconH) + CGFloat(3 * cellMargin) + textH + CGFloat(bottomBarH)
}
if pic_urls?.count > 0{
let picSize = calculateFrame()
picF = picSize.0
picItemSize = picSize.1
forwordBgF = picSize.2
_cellHeight = _cellHeight! + (picF?.size.height)! + CGFloat(cellMargin)
}
}
return _cellHeight
}
}
// 配图view的frame
var picF : CGRect?
// 转发微博view的背景frame
var forwordBgF : CGRect?
// 配图cell的itemSize
var picItemSize : CGSize?
init(dict : [String : AnyObject]){
super.init()
setValuesForKeys(dict)
}
// 对象中的属性和字典不完全匹配的时候要实现该方法,忽略找不到的key
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
override func setNilValueForKey(_ key: String) {
}
// KVC 的本质会依次调用该方法。判断若key为user,则转换成WBUser
override func setValue(_ value: Any?, forKey key: String) {
if key == "user"{
let user = WBUser.init(dict: value as! [String : AnyObject])
self.user = user
return;
}
if key == "retweeted_status" {
let status = WBStatus.init(dict: value as! [String : AnyObject])
self.forwordStatus = status
return;
}
if key == "bmiddle_pic" {
return;
}
super.setValue(value, forKey: key)
}
override var description: String {
let keys : [String] = ["created_at", "id", "source", "text", "pic_urls"]
let dict = dictionaryWithValues(forKeys: keys)
return ("\(dict)")
}
/**
获取微博数据
- parameter since_id: 下拉返回比since_id值大的微博
- parameter max_id: 上拉返回比max_id值小的微博
- parameter finished: 数据加载完成的回调闭包
*/
class func loadNewStatuses(_ max_id : String, since_id : String, finished : @escaping (_ dateArr : [WBStatus]?, _ error : Error?) -> ()){
WBStatusDAO.loadStatuses(since_id, max_id: max_id) { (JSONArr, error) in
if JSONArr != nil {
// 字典数组转模型数组
let statusArr : [WBStatus] = WBStatus.dictionaryArrToModelArr(JSONArr!)
// 调用闭包给外部传值
finished(statusArr, nil)
return
}
// 调用闭包给外部传值
finished(nil, error)
}
}
class func dictionaryArrToModelArr(_ dictArr : [[String : AnyObject]]) -> [WBStatus]{
// CSprint("----\(dictArr[0])")
var dateArr = [WBStatus]()
for dict in dictArr{
let status : WBStatus = WBStatus.init(dict: dict)
dateArr.append(status)
}
return dateArr
}
//根据模型计算配图frame、配图cell的itemSize、转发微博背景的frame、
fileprivate func calculateFrame() -> (CGRect , CGSize, CGRect){
let picsW = UIScreen.main.bounds.width - CGFloat(2 * cellMargin)
let picsH = picsW
// 文字的最大尺寸
let maxSize = CGSize(width: picsW, height: CGFloat(MAXFLOAT))
// 计算转发的高度
var forwordTextH : CGFloat = 0
if forwordStatus != nil {
if forwordStatus?.text != nil{
forwordTextH = ("@\(forwordStatus?.user?.screen_name):\(forwordStatus?.text)" as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17)], context: nil).size.height
}else{
forwordTextH = 0
}
}
// 计算文字的高度
var textH : CGFloat = 0
if text != nil{
textH = (text! as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17)], context: nil).size.height
}else{
textH = 0
}
if pic_urls?.count == 0{
if forwordStatus != nil{
return (CGRect.zero, CGSize.zero, CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height: CGFloat(2 * cellMargin) + forwordTextH))
}else{
return (CGRect.zero, CGSize.zero, CGRect.zero)
}
}
// 一张配图
if pic_urls?.count == 1{
// 取出缓存中的image计算size
let image = SDImageCache.shared().imageFromDiskCache(forKey: pic_urls?.first!["thumbnail_pic"] as! String)
var picY : CGFloat = 0
if forwordStatus != nil{
picY = CGFloat(iconH + (5 * cellMargin)) + forwordTextH + textH
if image != nil {
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: picY, width: image!.size.width * 2, height: image!.size.height * 2)
return (picRect, CGSize(width: image!.size.width * 2, height: image!.size.height * 2), CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height: image!.size.height * 2 + forwordTextH + CGFloat(3 * cellMargin)))
}else{
return (CGRect.zero, CGSize.zero, CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height:forwordTextH + CGFloat(3 * cellMargin)))
}
}else{
picY = CGFloat(iconH + (3 * cellMargin)) + textH
if image != nil {
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: picY, width: image!.size.width * 2, height: image!.size.height * 2)
return (picRect, CGSize(width: image!.size.width * 2, height: image!.size.height * 2), CGRect.zero)
}else{
return (CGRect.zero, CGSize.zero, CGRect.zero)
}
}
}else if pic_urls?.count == 4{
let itemSize = (picsW - CGFloat(cellMargin)) / 2
if forwordStatus != nil{
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (5 * cellMargin)) + textH + forwordTextH, width: picsW, height: picsH)
return (picRect, CGSize(width: itemSize, height: itemSize), CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height: picsH + forwordTextH + CGFloat(3 * cellMargin)))
}else{
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height: picsH)
return (picRect, CGSize(width: itemSize, height: itemSize), CGRect.zero)
}
}else{
let row = ((pic_urls?.count)! - 1) / 3 + 1
let col = ((pic_urls?.count)! - 1) % 3 + 1
let itemW = (picsW - CGFloat(2 * cellMargin)) / 3
let itemH = itemW
if forwordStatus != nil{
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (5 * cellMargin)) + textH + forwordTextH, width: CGFloat(col) * itemW + CGFloat((col - 1) * cellMargin), height: CGFloat(row) * itemH + CGFloat((row - 1) * cellMargin))
return (picRect, CGSize(width: itemW, height: itemH), CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: picsW, height: CGFloat(row) * itemH + CGFloat((row - 1) * cellMargin) + forwordTextH + CGFloat(3 * cellMargin)))
}else{
let picRect : CGRect = CGRect(x: CGFloat(cellMargin), y: CGFloat(iconH + (3 * cellMargin)) + textH, width: CGFloat(col) * itemW + CGFloat((col - 1) * cellMargin), height: CGFloat(row) * itemH + CGFloat((row - 1) * cellMargin))
return (picRect, CGSize(width: itemW, height: itemH), CGRect.zero)
}
}
}
}
| apache-2.0 | 40aee0fccecd5efd296c5dbc70d1023a | 34.517699 | 291 | 0.490657 | 4.388737 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | GeekSpeak Show Timer/Appearance.swift | 2 | 1451 | import UIKit
class Appearance {
struct Constants {
static let GeekSpeakBlueColor = UIColor(red: 14/255,
green: 115/255,
blue: 192/255,
alpha: 1.0)
static let GeekSpeakBlueInactiveColor = UIColor(red: 14/255,
green: 115/255,
blue: 115/255,
alpha: 0.2)
static let BreakColor = UIColor(red: 0.75,
green: 0.0,
blue: 0.0,
alpha: 1.0)
static let WarningColor = UIColor(red: 23/255,
green: 157/255,
blue: 172/255,
alpha: 1.0)
static let AlarmColor = UIColor(red: 30/255,
green: 226/255,
blue: 166/255,
alpha: 1.0)
static let RingWidth = CGFloat(0.257)
static let RingDarkeningFactor = CGFloat(1.0)
}
class func apply() {
UIButton.appearance().tintColor = Constants.GeekSpeakBlueColor
}
}
| mit | 4f93a99b002943bddc8cb4a2ebd3df6c | 36.205128 | 66 | 0.345279 | 5.995868 | false | false | false | false |
guidomb/Portal | Portal/View/UIKit/PortalViewController.swift | 1 | 10018 | //
// PortalViewController.swift
// PortalView
//
// Created by Guido Marucci Blas on 2/14/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
public final class PortalViewController<
MessageType,
RouteType,
CustomComponentRendererType: UIKitCustomComponentRenderer>: UIViewController
where CustomComponentRendererType.MessageType == MessageType, CustomComponentRendererType.RouteType == RouteType {
public struct ComponentPatch {
let changeSet: ComponentChangeSet<ActionType>
let component: Component<ActionType>
// It's really important for consistency that only code inside this controller is able
// to create instances of ComponentPatch.
//
// The role of this struct is to maintain consistency between the componenet the user
// wants to render and the change set to be applied to transition from the current
// rendered component (virtual view) to the next one.
//
// The controller does not expose the rendered component, so the only way to get a
// change set is through the PortalViewController#calculatePatch(for:) method which
// will create the appropiate ComponentPatch instance.
//
// Rendering a patch is only possible using PortalViewController#render(patch:) method
// which apart from applying the change set to the controller's view it will save
// the component for future change set generation
//
// The main reason behind separating change set generation from rendering is to be able
// to calculate change sets off the main thread. The problem, and the reason why ComponentPatch
// exists, is to make sure that the change set that will be applied was generated from
// the component inside the patch, which will then be referenced by the controller in order
// to calculate new change sets against other components threes.
//
// Bottom line we want to make sure that the component used when generating the change set
// is the same one that will be stored by the controller once the change set is applied.
fileprivate init(changeSet: ComponentChangeSet<ActionType>, component: Component<ActionType>) {
self.changeSet = changeSet
self.component = component
}
}
public typealias ActionType = Action<RouteType, MessageType>
public typealias ComponentRenderer = UIKitComponentRenderer<MessageType, RouteType, CustomComponentRendererType>
public typealias CustomComponentRendererFactory = (ContainerController) -> CustomComponentRendererType
internal typealias InternalActionType = InternalAction<RouteType, MessageType>
public let mailbox: Mailbox<ActionType>
public var orientation: SupportedOrientations = .all
internal let internalMailbox = Mailbox<InternalActionType>()
fileprivate var disposers: [String : () -> Void] = [:]
private var component: Component<ActionType>
private var renderer: ComponentRenderer!
public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return orientation.uiInterfaceOrientation
}
public init(
component: Component<ActionType>,
layoutEngine: LayoutEngine = YogaLayoutEngine(),
customComponentRendererFactory: @escaping CustomComponentRendererFactory) {
self.component = component
self.mailbox = internalMailbox.filterMap { message in
if case .action(let action) = message {
return action
} else {
return .none
}
}
super.init(nibName: nil, bundle: nil)
self.renderer = ComponentRenderer(layoutEngine: layoutEngine) { [unowned self] in
customComponentRendererFactory(self)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
disposers.values.forEach { $0() }
}
public override func loadView() {
super.loadView()
}
public override func viewDidLoad() {
// Not really sure why this is necessary but some users where having
// issues when pushing controllers into Portal's navigation controller.
// For some reason the pushed controller's view was being positioned
// at {0,0} instead at {0, statusBarHeight + navBarHeight}. What was
// even weirder was that this did not happend for all users.
// This setting seems to fix the issue.
edgesForExtendedLayout = []
render()
}
public func render() {
// For some reason we need to calculate the view's frame
// when updating a contained controller's view whos
// parent is a navigation controller because if not the view
// does not take into account the navigation and status bar in order
// to sets its visible size.
view.frame = calculateViewFrame()
let componentMailbox = renderer.render(component: component, into: view)
componentMailbox.forwardMap(to: internalMailbox) { .action($0) }
}
public func calculatePatch(for component: Component<ActionType>) -> ComponentPatch {
let changeSet = self.component.changeSet(for: component)
return ComponentPatch(changeSet: changeSet, component: component)
}
public func render(patch: ComponentPatch) {
// Because nobody outside this file is able to create
// instances of ComponentPatch it is guaranteed
// that the patch's component was the one used
// to generate the patch's change set.
component = patch.component
renderer.apply(changeSet: patch.changeSet, to: view)
}
}
extension PortalViewController: ContainerController {
public func registerDisposer(for identifier: String, disposer: @escaping () -> Void) {
disposers[identifier] = disposer
}
}
fileprivate extension PortalViewController {
fileprivate var statusBarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.size.height
}
/// The bounds of the container view used to render the controller's component
/// needs to be calcuated using this method because if the component is redenred
/// on the viewDidLoad method for some reason UIKit reports the controller's view bounds
/// to be equal to the screen's frame. Which does not take into account the status bar
/// nor the navigation bar if the controllers is embeded inside a navigation controller.
///
/// Also the supported orientation should be taken into account in order to define the bound's
/// width and height. The supported orientation has higher priority to the device's orientation
/// unless the supported orientation is all.
///
/// The funny thing is that if you ask for the controller's view bounds inside viewWillAppear
/// the bounds are properly set but the component needs to be rendered cannot be rendered in
/// viewWillAppear because some views, like UITableView have unexpected behavior.
///
/// - Returns: The view bounds that should be used to render the component's view
fileprivate func calculateViewFrame() -> CGRect {
var bounds = UIScreen.main.bounds
if isViewInLandscapeOrientation() {
// We need to check if the bounds has already been swapped.
// After the device has been effectively been set in landscape mode
// either by rotation the device of by forcing the supported orientation
// UIKit returns the bounds size already swapped but the first time we
// are forcing a landscape orientation we need to swap them manually.
if bounds.size.width < bounds.height {
bounds.size = bounds.size.swapped()
}
if let navBarBounds = navigationController?.navigationBar.bounds {
bounds.size.width -= statusBarHeight + navBarBounds.size.height
bounds.origin.x += statusBarHeight + navBarBounds.size.height
}
} else if let navBarBounds = navigationController?.navigationBar.bounds {
// FIXME There is a bug that needs to be solved regarding the status
// bug. When a modal landscape controller is being presented on top
// of a portrait navigation controller, because in landscape mode the
// status bar is not present, UIKit decides to hide the status bar before
// performing the transition animation to present the modal controller.
//
// This has the effect of making the view bounds bigger because the
// status bar is not visible anymore and because we do not perform
// a re-layout, the view endups being moved to the new origin and
// a black space appears at the bottom of the view.
//
// A possible solution would be to detect when a modal landscape
// controller is being presented and then re-render the view which
// would trigger a calculation of the layout that would take
// into account the update view's bounds.
bounds.size.height -= statusBarHeight + navBarBounds.size.height
bounds.origin.y += statusBarHeight + navBarBounds.size.height
}
return bounds
}
fileprivate func isViewInLandscapeOrientation() -> Bool {
switch orientation {
case .landscape:
return true
case .portrait:
return false
case .all:
return UIDevice.current.orientation.isLandscape
}
}
}
fileprivate extension CGSize {
func swapped() -> CGSize {
return CGSize(width: height, height: width)
}
}
| mit | 966463659c47abb1b4cbdedeea9523e9 | 43.127753 | 118 | 0.669063 | 5.488767 | false | false | false | false |
WeltN24/Carlos | Sources/Carlos/CacheLevels/NSUserDefaultsCacheLevel.swift | 1 | 5523 | import Combine
import Foundation
/**
Default name for the persistent domain used by the NSUserDefaultsCacheLevel
Keep in mind that using this domain for multiple cache levels at the same time could lead to undesired results!
For example, if one of the cache levels get cleared, also the other will be affected unless they save something before leaving the app.
The behavior is not 100% certain and this possibility is discouraged.
*/
public let DefaultUserDefaultsDomainName = "CarlosPersistentDomain"
/// This class is a NSUserDefaults cache level. It has a configurable domain name so that multiple levels can be included in the same sandboxed app.
public final class NSUserDefaultsCacheLevel<K: StringConvertible, T: NSCoding>: CacheLevel {
/// The key type of the cache, should be convertible to String values
public typealias KeyType = K
/// The output type of the cache, should conform to NSCoding
public typealias OutputType = T
private let domainName: String
private let lock: UnfairLock
private let userDefaults: UserDefaults
private var internalDomain: [String: Data]?
private var safeInternalDomain: [String: Data] {
if let internalDomain = internalDomain {
return internalDomain
} else {
let fetchedDomain = (userDefaults.persistentDomain(forName: domainName) as? [String: Data]) ?? [:]
internalDomain = fetchedDomain
return fetchedDomain
}
}
/**
Creates a new instance of this NSUserDefaults-based cache level.
- parameter name: The name to use for the persistent domain on NSUserDefaults. Should be unique in your sandboxed app
*/
public init(name: String = DefaultUserDefaultsDomainName) {
domainName = name
lock = UnfairLock()
userDefaults = UserDefaults.standard
internalDomain = safeInternalDomain
}
/**
Sets a new value for the given key
- parameter value: The value to set for the given key
- parameter key: The key you want to set
This method will convert the value to NSData by using NSCoding and save the data on the persistent domain.
A soft-cache is used to avoid hitting the persistent domain everytime you are going to fetch values from this cache. The operation is thread-safe
*/
public func set(_ value: OutputType, forKey key: KeyType) -> AnyPublisher<Void, Error> {
AnyPublisher.create { [weak self] promise in
guard let self = self else {
return
}
var softCache = self.safeInternalDomain
Logger.log("Setting a value for the key \(key.toString()) on the user defaults cache \(self)")
if let data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false) {
softCache[key.toString()] = data
self.internalDomain = softCache
self.userDefaults.setPersistentDomain(softCache, forName: self.domainName)
promise(.success(()))
} else {
Logger.log("Failed setting a value for the key \(key.toString()) on the user defaults cache \(self)")
promise(.failure(FetchError.invalidCachedData))
}
}
.eraseToAnyPublisher()
}
/**
Fetches a value on the persistent domain for the given key
- parameter key: The key you want to fetch
- returns: The result of this fetch on the cache
A soft-cache is used to avoid hitting the persistent domain everytime. This operation is thread-safe
*/
public func get(_ key: KeyType) -> AnyPublisher<OutputType, Error> {
AnyPublisher.create { [weak self] promise in
guard let self = self else {
return
}
if let cachedValue = self.safeInternalDomain[key.toString()] {
if let unencodedObject = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(cachedValue) as? T {
Logger.log("Fetched \(key.toString()) on user defaults level (domain \(self.domainName)")
promise(.success(unencodedObject))
} else {
Logger.log("Failed fetching \(key.toString()) on the user defaults cache (domain \(self.domainName), corrupted data")
promise(.failure(FetchError.invalidCachedData))
}
} else {
Logger.log("Failed fetching \(key.toString()) on the user defaults cache (domain \(self.domainName), no data")
promise(.failure(FetchError.valueNotInCache))
}
}
.eraseToAnyPublisher()
}
/**
Completely clears the contents of this cache
Please keep in mind that if the same name is used for multiple cache levels, the contents of these caches will also be cleared, at least from a persistence point of view.
The soft caches of the other levels will still contain consistent values, though, so setting a value on one of these levels will result in the whole previous content of the cache to be persisted on NSUserDefaults, even this may or may not be the desired behavior.
The conclusion is that you should only use the same name for multiple cache levels if you are aware of the consequences. In general the behavior may not be the expected one.
The operation is thread-safe
*/
public func clear() {
lock.locked {
userDefaults.removePersistentDomain(forName: domainName)
internalDomain = [:]
}
}
/**
Clears the contents of the soft cache for this cache level.
Fetching or setting a value after this call is safe, since the content will be pre-fetched from the disk immediately before.
The operation is thread-safe
*/
public func onMemoryWarning() {
lock.locked {
internalDomain = nil
}
}
}
| mit | 6190df48c2414f62bc7e96bc0ac2a739 | 37.894366 | 266 | 0.714286 | 4.790113 | false | false | false | false |
basheersubei/swift-t | stc/tests/480-size.swift | 4 | 444 |
import assert;
main
{
int x[] = [1:15];
assertEqual(15, size(x), "size(x)");
int y[] = [-1:12:2];
assertEqual(7, size(y), "size(y)");
assertEqual(0, size([10:1]), "start > end");
assertEqual(1, size([1:1]), "start == end");
assertEqual(0, size([1:0]), "start == end + 1");
assertEqual(1, size([3:5:3]), "test step 1");
assertEqual(2, size([3:6:3]), "test step 2");
assertEqual(2, size([3:7:3]), "test step 3");
}
| apache-2.0 | f3d7103ef8af3c26b2192d923d96882f | 20.142857 | 50 | 0.540541 | 2.674699 | false | true | false | false |
XLabKC/Badger | Badger/Badger/SelectUserViewController.swift | 1 | 4372 | import UIKit
protocol SelectUserDelegate: class {
func selectedUser(user: User)
}
class SelectUserViewController: UITableViewController {
private var teamsObserver: FirebaseListObserver<Team>?
private var usersObserver: FirebaseListObserver<User>?
private var users = [User]()
private var teamIds: [String]?
weak var delegate: SelectUserDelegate?
deinit {
self.dispose()
}
override func viewDidLoad() {
self.navigationItem.titleView = Helpers.createTitleLabel("Select User")
let userCellNib = UINib(nibName: "UserCell", bundle: nil)
self.tableView.registerNib(userCellNib, forCellReuseIdentifier: "UserCell")
let loadingCellNib = UINib(nibName: "LoadingCell", bundle: nil)
self.tableView.registerNib(loadingCellNib, forCellReuseIdentifier: "LoadingCell")
super.viewDidLoad()
}
func setTeamIds(ids: [String]) {
self.teamIds = ids
self.dispose()
let usersRef = Firebase(url: Global.FirebaseUsersUrl)
self.usersObserver = FirebaseListObserver<User>(ref: usersRef, onChanged: self.usersChanged)
self.usersObserver!.comparisonFunc = { (a, b) -> Bool in
return a.fullName < b.fullName
}
let teamsRef = Firebase(url: Global.FirebaseTeamsUrl)
self.teamsObserver = FirebaseListObserver<Team>(ref: teamsRef, keys: ids, onChanged: self.teamsChanged)
}
private func teamsChanged(teams: [Team]) {
if let observer = self.usersObserver {
var uids = [String: Bool]()
for team in teams {
for member in team.memberIds.keys {
uids[member] = true
}
}
observer.setKeys(uids.keys.array)
}
}
private func usersChanged(users: [User]) {
let oldUsers = self.users
self.users = users
if !self.isViewLoaded() {
return
}
if oldUsers.isEmpty {
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Fade)
} else {
var updates = Helpers.diffArrays(oldUsers, end: users, section: 0, compare: { (a, b) -> Bool in
return a.uid == b.uid
})
if !updates.inserts.isEmpty || !updates.deletes.isEmpty {
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths(updates.deletes, withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths(updates.inserts, withRowAnimation: .Fade)
self.tableView.endUpdates()
}
for (index, user) in enumerate(users) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? UserCell {
cell.setTopBorder(index == 0 ? .Full : .None)
cell.setUid(user.uid)
}
}
}
}
// TableViewController Overrides
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.isEmpty ? 1 : users.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == 0 && self.users.isEmpty) {
return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! LoadingCell
}
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell") as! UserCell
cell.arrowImage.hidden = true
cell.setTopBorder(indexPath.row == 0 ? .Full : .None)
cell.setUid(self.users[indexPath.row].uid)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let delegate = self.delegate {
delegate.selectedUser(self.users[indexPath.row])
}
self.navigationController?.popViewControllerAnimated(true)
}
private func dispose() {
if let observer = self.teamsObserver {
observer.dispose()
}
if let observer = self.usersObserver {
observer.dispose()
}
}
} | gpl-2.0 | 3bd2112c08a7eacc269ac992448af235 | 34.552846 | 118 | 0.624886 | 4.868597 | false | false | false | false |
kevinli194/CancerCenterPrototype | CancerInstituteDemo/CancerInstituteDemo/AppointmentTableViewController.swift | 1 | 7299 | //
// AppointmentTableViewController.swift
// CancerInstituteDemo
//
// Created by Anna Benson on 11/11/15.
// Copyright © 2015 KAG. All rights reserved.
//
import UIKit
class AppointmentTableViewController : UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
var providers = [Provider]()
var filteredProviders = [Provider]()
override func viewDidLoad() {
super.viewDidLoad()
//navigation bar background
self.navigationController?.navigationBar.barTintColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!)
//full view background
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!)
//load all of the provides into table view
self.providers = [Provider(name:"J. Abbruzzese", clinic:"Clinic 3-2", time:0),
Provider(name:"R. Bain", clinic:"Clinic 3-2", time:60),
Provider(name:"A. Berchuck", clinic:"Clinic 2-2", time:15),
Provider(name:"M. Berry", clinic:"Clinic 3-2", time:10),
Provider(name:"K. Blackwell", clinic:"Clinic 2-2", time:0),
Provider(name:"D. Blazer", clinic:"Clinic 3-2", time:15),
Provider(name:"A. Desjardins", clinic:"Clinic 3-1", time:20),
Provider(name:"A. Friedman", clinic:"Clinic 2-2", time:0),
Provider(name:"H. Friedman", clinic:"Clinic 3-2", time:60),
Provider(name:"R. Greenup", clinic:"Clinic 2-2", time:0),
Provider(name:"B. Hanks", clinic:"Clinic 3-2", time:40),
Provider(name:"D. Harpole", clinic:"Clinic 3-2", time:0),
Provider(name:"M. Hartwig", clinic:"Clinic 3-2", time:0),
Provider(name:"S. Hwang", clinic:"Clinic 2-2", time:0),
Provider(name:"A. Kamal", clinic:"Clinic 3-2", time:90),
Provider(name:"C. Kelsey", clinic:"Clinic 3-2", time:0),
Provider(name:"G. Kimmick", clinic:"Clinic 2-2", time:0),
Provider(name:"P. Lee", clinic:"Clinic 2-2", time:15),
Provider(name:"C. Mantyh", clinic:"Clinic 3-2", time:0),
Provider(name:"P. Marcom", clinic:"Clinic 2-2", time:0),
Provider(name:"P. Mosca", clinic:"Clinic 3-2", time:20),
Provider(name:"M. Onaitis", clinic:"Clinic 3-2", time:10),
Provider(name:"J. Perkins", clinic:"Clinic 2-2", time:60),
Provider(name:"N. Ready", clinic:"Clinic 3-2", time:0),
Provider(name:"S. Roman", clinic:"Clinic 2-2", time:0),
Provider(name:"A. Salama", clinic:"Clinic 3-2", time:0),
Provider(name:"J. Sampson", clinic:"Clinic 3-1", time:0),
Provider(name:"R. Scheri", clinic:"Clinic 2-2", time:20),
Provider(name:"A. Secord", clinic:"Clinic 2-2", time:0),
Provider(name:"J. Sosa", clinic:"Clinic 2-2", time:40),
Provider(name:"M. Wahidi", clinic:"Clinic 3-2", time:90),
Provider(name:"M. Zenn", clinic:"Clinic 2-2", time:0)]
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//filteredProviders is with one of the clinics chosen
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.filteredProviders.count
} else {
return self.providers.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//put array of provides into the table
let cell = self.tableView.dequeueReusableCellWithIdentifier("AppointmentTableViewCell", forIndexPath: indexPath) as UITableViewCell
var doctor : Provider
if tableView == self.searchDisplayController!.searchResultsTableView {
doctor = filteredProviders[indexPath.row]
} else {
doctor = providers[indexPath.row]
}
//cell background & text color
cell.textLabel!.text = doctor.name
cell.textLabel!.textColor = UIColor.whiteColor()
cell.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("ShowAppointmentDetails", sender: tableView)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
//setup segues to detail provides -> filteredProviders is with one of the clinics chosen
if segue.identifier == "ShowAppointmentDetails" {
let appointmentDetailViewController = segue.destinationViewController as! AppointmentController
if sender as! UITableView == self.searchDisplayController!.searchResultsTableView {
let indexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow!
appointmentDetailViewController.myProvider = self.filteredProviders[indexPath.row].name
appointmentDetailViewController.myClinic = self.filteredProviders[indexPath.row].clinic
appointmentDetailViewController.myTime = self.filteredProviders[indexPath.row].time
} else {
let indexPath = self.tableView.indexPathForSelectedRow!
appointmentDetailViewController.myProvider = self.providers[indexPath.row].name
appointmentDetailViewController.myClinic = self.providers[indexPath.row].clinic
appointmentDetailViewController.myTime = self.providers[indexPath.row].time
}
}
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
//filtering doctors by clinic feature
self.filteredProviders = self.providers.filter({( doctor: Provider) -> Bool in
let categoryMatch = (scope == "All") || (doctor.clinic == scope)
let stringMatch = doctor.name.rangeOfString(searchText)
return categoryMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String?) -> Bool {
let scopes = self.searchDisplayController!.searchBar.scopeButtonTitles! as [String]
let selectedScope = scopes[self.searchDisplayController!.searchBar.selectedScopeButtonIndex] as String
self.filterContentForSearchText(searchString!, scope: selectedScope)
return true
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
let scope = self.searchDisplayController!.searchBar.scopeButtonTitles! as [String]
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text!, scope: scope[searchOption])
return true
}
}
| mit | a61ea62a1d8bff51c9cab2839dc38d67 | 50.034965 | 139 | 0.652508 | 4.354415 | false | false | false | false |
HKMOpen/actor-platform | actor-apps/app-ios/ActorSwift/Utils.swift | 9 | 1875 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class Utils: NSObject {
class func isRetina() -> Bool {
return UIScreen.mainScreen().scale > 1
}
class func retinaPixel() -> CGFloat {
if Utils.isRetina() {
return 0.5
}
return 1.0
}
}
extension Array {
func contains<T where T : Equatable>(obj: T) -> Bool {
return self.filter({$0 as? T == obj}).count > 0
}
}
extension UIViewController {
func getNavigationBarHeight() -> CGFloat {
if (navigationController != nil) {
return navigationController!.navigationBar.frame.height
} else {
return CGFloat(44)
}
}
func getStatusBarHeight() -> CGFloat {
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
return min(statusBarSize.width, statusBarSize.height)
}
}
extension NSTimeInterval {
var time:String {
return String(format:"%02d:%02d:%02d.%03d", Int((self/3600.0)%60),Int((self/60.0)%60), Int((self) % 60 ), Int(self*1000 % 1000 ) )
}
}
func log(text:String) {
NSLog(text)
}
func localized(text: String) -> String {
return NSLocalizedString(text, comment: "")
}
typealias cancellable_closure = (() -> ())?
func dispatch_after(#seconds:Double, queue: dispatch_queue_t = dispatch_get_main_queue(), closure:()->()) -> cancellable_closure {
var cancelled = false
let cancel_closure: cancellable_closure = {
cancelled = true
}
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue, {
if !cancelled {
closure()
}
}
)
return cancel_closure
}
func cancel_dispatch_after(cancel_closure: cancellable_closure) {
cancel_closure?()
} | mit | 9c1b54941ffdb7fbde8cefdcdc465b37 | 22.45 | 138 | 0.5936 | 4.058442 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/QuickStartTours.swift | 1 | 29586 | import Gridicons
import Foundation
import UIKit
protocol QuickStartTour {
typealias WayPoint = (element: QuickStartTourElement, description: NSAttributedString)
var key: String { get }
var title: String { get }
var titleMarkedCompleted: String { get } // assists VoiceOver users
var analyticsKey: String { get }
var description: String { get }
var icon: UIImage { get }
var iconColor: UIColor { get }
var suggestionNoText: String { get }
var suggestionYesText: String { get }
var waypoints: [WayPoint] { get set }
var accessibilityHintText: String { get }
var showWaypointNotices: Bool { get }
var taskCompleteDescription: NSAttributedString? { get }
var showDescriptionInQuickStartModal: Bool { get }
/// Represents where the tour can be shown from.
var possibleEntryPoints: Set<QuickStartTourEntryPoint> { get }
var mustBeShownInBlogDetails: Bool { get }
}
extension QuickStartTour {
var waypoints: [WayPoint] {
get {
return []
}
}
var showWaypointNotices: Bool {
get {
return true
}
}
var taskCompleteDescription: NSAttributedString? {
get {
return nil
}
}
var mustBeShownInBlogDetails: Bool {
get {
return possibleEntryPoints == [.blogDetails]
}
}
var showDescriptionInQuickStartModal: Bool {
get {
return false
}
}
}
private struct Strings {
static let notNow = NSLocalizedString("Not now", comment: "Phrase displayed to dismiss a quick start tour suggestion.")
static let yesShowMe = NSLocalizedString("Yes, show me", comment: "Phrase displayed to begin a quick start tour that's been suggested.")
}
struct QuickStartSiteMenu {
private static let descriptionBase = NSLocalizedString("Select %@ to continue.", comment: "A step in a guided tour for quick start. %@ will be the name of the segmented control item to select on the Site Menu screen.")
private static let descriptionTarget = NSLocalizedString("Menu", comment: "The segmented control item to select during a guided tour.")
static let waypoint = QuickStartTour.WayPoint(element: .siteMenu, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: nil))
}
struct QuickStartChecklistTour: QuickStartTour {
let key = "quick-start-checklist-tour"
let analyticsKey = "view_list"
let title = NSLocalizedString("Continue with site setup", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Continue with site setup", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Time to finish setting up your site! Our checklist walks you through the next steps.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.external)
let iconColor = UIColor.systemGray4
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to see your checklist", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Quick Start", comment: "The menu item to select during a guided tour.")
return [(element: .checklist, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.listCheckmark)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of setting up your site.", comment: "This value is used to set the accessibility hint text for setting up the user's site.")
}
struct QuickStartCreateTour: QuickStartTour {
let key = "quick-start-create-tour"
let analyticsKey = "create_site"
let title = NSLocalizedString("Create your site", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Create your site", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Get your site up and running", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.plus)
let iconColor = UIColor.systemGray4
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [QuickStartTour.WayPoint] = [(element: .noSuchElement, description: NSAttributedString(string: "This tour should never display as interactive."))]
let accessibilityHintText = NSLocalizedString("Guides you through the process of creating your site.", comment: "This value is used to set the accessibility hint text for creating the user's site.")
}
struct QuickStartViewTour: QuickStartTour {
let key = "quick-start-view-tour"
let analyticsKey = "view_site"
let title = NSLocalizedString("View your site", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: View your site", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Preview your site to see what your visitors will see.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.external)
let iconColor = UIColor.muriel(color: MurielColor(name: .yellow, shade: .shade20))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint]
let accessibilityHintText = NSLocalizedString("Guides you through the process of previewing your site.", comment: "This value is used to set the accessibility hint text for previewing a user's site.")
init(blog: Blog) {
let descriptionBase = NSLocalizedString("Select %@ to view your site", comment: "A step in a guided tour for quick start. %@ will be the site url.")
let placeholder = NSLocalizedString("Site URL", comment: "The item to select during a guided tour.")
let descriptionTarget = (blog.displayURL as String?) ?? placeholder
self.waypoints = [
(element: .viewSite, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: nil))
]
}
}
struct QuickStartThemeTour: QuickStartTour {
let key = "quick-start-theme-tour"
let analyticsKey = "browse_themes"
let title = NSLocalizedString("Choose a theme", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Choose a theme", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Browse all our themes to find your perfect fit.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.themes)
let iconColor = UIColor.systemGray4
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails]
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to discover new themes", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Themes", comment: "The menu item to select during a guided tour.")
return [(element: .themes, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.themes)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of choosing a theme for your site.", comment: "This value is used to set the accessibility hint text for choosing a theme for the user's site.")
}
struct QuickStartShareTour: QuickStartTour {
let key = "quick-start-share-tour"
let analyticsKey = "share_site"
let title = NSLocalizedString("Social sharing", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Social sharing", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Automatically share new posts to your social media accounts.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.share)
let iconColor = UIColor.muriel(color: MurielColor(name: .blue, shade: .shade40)).color(for: UITraitCollection(userInterfaceStyle: .light))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails]
var waypoints: [WayPoint] = {
let step1DescriptionBase = NSLocalizedString("Select %@ to continue", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step1DescriptionTarget = NSLocalizedString("Sharing", comment: "The menu item to select during a guided tour.")
let step1: WayPoint = (element: .sharing, description: step1DescriptionBase.highlighting(phrase: step1DescriptionTarget, icon: .gridicon(.share)))
let step2DescriptionBase = NSLocalizedString("Select the %@ to add your social media accounts", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step2DescriptionTarget = NSLocalizedString("connections", comment: "The menu item to select during a guided tour.")
let step2: WayPoint = (element: .connections, description: step2DescriptionBase.highlighting(phrase: step2DescriptionTarget, icon: nil))
return [step1, step2]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of creating a new page for your site.", comment: "This value is used to set the accessibility hint text for creating a new page for the user's site.")
}
struct QuickStartPublishTour: QuickStartTour {
let key = "quick-start-publish-tour"
let analyticsKey = "publish_post"
let title = NSLocalizedString("Publish a post", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Publish a post", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Draft and publish a post.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.create)
let iconColor = UIColor.muriel(color: MurielColor(name: .green, shade: .shade30))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let showWaypointNotices = false
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to create a new post", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
return [(element: .newpost, description: descriptionBase.highlighting(phrase: "", icon: .gridicon(.create)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of publishing a new post on your site.", comment: "This value is used to set the accessibility hint text for publishing a new post on the user's site.")
}
struct QuickStartFollowTour: QuickStartTour {
let key = "quick-start-follow-tour"
let analyticsKey = "follow_site"
let title = NSLocalizedString("Connect with other sites", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Connect with other sites", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Discover and follow sites that inspire you.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.readerFollow)
let iconColor = UIColor.muriel(color: MurielColor(name: .pink, shade: .shade40))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint] = {
let step1DescriptionBase = NSLocalizedString("Select %@ to find other sites.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step1DescriptionTarget = NSLocalizedString("Reader", comment: "The menu item to select during a guided tour.")
let step1: WayPoint = (element: .readerTab, description: step1DescriptionBase.highlighting(phrase: step1DescriptionTarget, icon: .gridicon(.reader)))
let step2DiscoverDescriptionBase = NSLocalizedString("Use %@ to find sites and tags.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step2DiscoverDescriptionTarget = NSLocalizedString("Discover", comment: "The menu item to select during a guided tour.")
let step2DiscoverDescription = step2DiscoverDescriptionBase.highlighting(phrase: step2DiscoverDescriptionTarget, icon: nil)
let step2SettingsDescriptionBase = NSLocalizedString("Try selecting %@ to add topics you like.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step2SettingsDescriptionTarget = NSLocalizedString("Settings", comment: "The menu item to select during a guided tour.")
let step2SettingsDescription = step2SettingsDescriptionBase.highlighting(phrase: step2SettingsDescriptionTarget, icon: .gridicon(.cog))
/// Combined description for step 2
let step2Format = NSAttributedString(string: "%@ %@")
let step2Description = NSAttributedString(format: step2Format, args: step2DiscoverDescription, step2SettingsDescription)
let step2: WayPoint = (element: .readerDiscoverSettings, description: step2Description)
return [step1, step2]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of following other sites.", comment: "This value is used to set the accessibility hint text for following the sites of other users.")
func setupReaderTab() {
guard let tabBar = WPTabBarController.sharedInstance() else {
return
}
tabBar.resetReaderTab()
}
}
struct QuickStartSiteTitleTour: QuickStartTour {
let key = "quick-start-site-title-tour"
let analyticsKey = "site_title"
let title = NSLocalizedString("Check your site title", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Check your site title", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Give your site a name that reflects its personality and topic. First impressions count!",
comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.pencil)
let iconColor = UIColor.muriel(color: MurielColor(name: .red, shade: .shade40))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint]
let accessibilityHintText = NSLocalizedString("Guides you through the process of setting a title for your site.", comment: "This value is used to set the accessibility hint text for setting the site title.")
init(blog: Blog) {
let descriptionBase = NSLocalizedString("Select %@ to set a new title.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let placeholder = NSLocalizedString("Site Title", comment: "The item to select during a guided tour.")
let descriptionTarget = blog.title ?? placeholder
self.waypoints = [
(element: .siteTitle, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: nil))
]
}
}
struct QuickStartSiteIconTour: QuickStartTour {
let key = "quick-start-site-icon-tour"
let analyticsKey = "site_icon"
let title = NSLocalizedString("Choose a unique site icon", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Choose a unique site icon", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Used across the web: in browser tabs, social media previews, and the WordPress.com Reader.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.globe)
let iconColor = UIColor.muriel(color: MurielColor(name: .purple, shade: .shade40))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
let showDescriptionInQuickStartModal = true
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to upload a new one.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Your Site Icon", comment: "The item to select during a guided tour.")
return [(element: .siteIcon, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: nil))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of uploading an icon for your site.", comment: "This value is used to set the accessibility hint text for uploading a site icon.")
}
struct QuickStartReviewPagesTour: QuickStartTour {
let key = "quick-start-review-pages-tour"
let analyticsKey = "review_pages"
let title = NSLocalizedString("Review site pages", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Review site pages", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Change, add, or remove your site's pages.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.pages)
let iconColor = UIColor.muriel(color: MurielColor(name: .celadon, shade: .shade30))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails]
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to see your page list.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Pages", comment: "The item to select during a guided tour.")
return [(element: .pages, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.pages)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of creating a new page for your site.", comment: "This value is used to set the accessibility hint text for creating a new page for the user's site.")
}
struct QuickStartCheckStatsTour: QuickStartTour {
let key = "quick-start-check-stats-tour"
let analyticsKey = "check_stats"
let title = NSLocalizedString("Check your site stats", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Check your site stats", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Keep up to date on your site’s performance.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.statsAlt)
let iconColor = UIColor.muriel(color: MurielColor(name: .orange, shade: .shade30))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var taskCompleteDescription: NSAttributedString? = {
let descriptionBase = NSLocalizedString("%@ Return to My Site screen when you're ready for the next task.", comment: "Title of the task complete hint for the Quick Start Tour")
let descriptionTarget = NSLocalizedString("Task complete.", comment: "A hint about the completed guided tour.")
return descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.checkmark))
}()
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to see how your site is performing.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Stats", comment: "The item to select during a guided tour.")
return [(element: .stats, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.stats)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of reviewing statistics for your site.", comment: "This value is used to set the accessibility hint text for viewing Stats on the user's site.")
}
struct QuickStartExplorePlansTour: QuickStartTour {
let key = "quick-start-explore-plans-tour"
let analyticsKey = "explore_plans"
let title = NSLocalizedString("Explore plans", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Explore plans", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Learn about the marketing and SEO tools in our paid plans.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.plans)
let iconColor = UIColor.systemGray4
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails]
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select %@ to see your current plan and other available plans.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Plan", comment: "The item to select during a guided tour.")
return [(element: .plans, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.plans)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of exploring plans for your site.", comment: "This value is used to set the accessibility hint text for exploring plans on the user's site.")
}
struct QuickStartNotificationsTour: QuickStartTour {
let key = "quick-start-notifications-tour"
let analyticsKey = "notifications"
let title = NSLocalizedString("Check your notifications", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Check your notifications", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Get real time updates from your pocket.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.bell)
let iconColor = UIColor.muriel(color: MurielColor(name: .purple, shade: .shade40))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var taskCompleteDescription: NSAttributedString? = {
let descriptionBase = NSLocalizedString("%@ Tip: get updates faster by enabling push notifications.", comment: "Title of the task complete hint for the Quick Start Tour")
let descriptionTarget = NSLocalizedString("Task complete.", comment: "A hint about the completed guided tour.")
return descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.checkmark))
}()
var waypoints: [WayPoint] = {
let descriptionBase = NSLocalizedString("Select the %@ tab to get updates on the go.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let descriptionTarget = NSLocalizedString("Notifications", comment: "The item to select during a guided tour.")
return [(element: .notifications, description: descriptionBase.highlighting(phrase: descriptionTarget, icon: .gridicon(.bell)))]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of checking your notifications.", comment: "This value is used to set the accessibility hint text for viewing the user's notifications.")
}
struct QuickStartMediaUploadTour: QuickStartTour {
let key = "quick-start-media-upload-tour"
let analyticsKey = "media"
let title = NSLocalizedString("Upload photos or videos", comment: "Title of a Quick Start Tour")
let titleMarkedCompleted = NSLocalizedString("Completed: Upload photos or videos", comment: "The Quick Start Tour title after the user finished the step.")
let description = NSLocalizedString("Bring media straight from your device or camera to your site.", comment: "Description of a Quick Start Tour")
let icon = UIImage.gridicon(.addImage)
let iconColor = UIColor.muriel(color: MurielColor(name: .celadon, shade: .shade30))
let suggestionNoText = Strings.notNow
let suggestionYesText = Strings.yesShowMe
let possibleEntryPoints: Set<QuickStartTourEntryPoint> = [.blogDetails, .blogDashboard]
var waypoints: [WayPoint] = {
let step1DescriptionBase = NSLocalizedString("Select %@ to see your current library.", comment: "A step in a guided tour for quick start. %@ will be the name of the item to select.")
let step1DescriptionTarget = NSLocalizedString("Media", comment: "The menu item to select during a guided tour.")
let step1: WayPoint = (element: .mediaScreen, description: step1DescriptionBase.highlighting(phrase: step1DescriptionTarget, icon: .gridicon(.image)))
let step2DescriptionBase = NSLocalizedString("Select %@to upload media. You can add it to your posts / pages from any device.", comment: "A step in a guided tour for quick start. %@ will be a plus icon.")
let step2DescriptionTarget = ""
let step2: WayPoint = (element: .mediaUpload, description: step2DescriptionBase.highlighting(phrase: step2DescriptionTarget, icon: .gridicon(.plus)))
return [step1, step2]
}()
let accessibilityHintText = NSLocalizedString("Guides you through the process of uploading new media.", comment: "This value is used to set the accessibility hint text for viewing the user's notifications.")
}
private extension String {
func highlighting(phrase: String, icon: UIImage?) -> NSAttributedString {
let normalParts = components(separatedBy: "%@")
guard normalParts.count > 0 else {
// if the provided base doesn't contain %@ then we don't know where to place the highlight
return NSAttributedString(string: self)
}
let resultString = NSMutableAttributedString(string: normalParts[0], attributes: [.font: Fonts.regular])
let highlightStr = NSAttributedString(string: phrase, attributes: [.foregroundColor: Appearance.highlightColor, .font: Fonts.highlight])
if let icon = icon {
let iconAttachment = NSTextAttachment()
iconAttachment.image = icon.withTintColor(Appearance.highlightColor)
iconAttachment.bounds = CGRect(x: 0.0, y: Fonts.regular.descender + Appearance.iconOffset, width: Appearance.iconSize, height: Appearance.iconSize)
let iconStr = NSAttributedString(attachment: iconAttachment)
switch UIView.userInterfaceLayoutDirection(for: .unspecified) {
case .rightToLeft:
resultString.append(highlightStr)
resultString.append(NSAttributedString(string: " "))
resultString.append(iconStr)
default:
resultString.append(iconStr)
resultString.append(NSAttributedString(string: " "))
resultString.append(highlightStr)
}
} else {
resultString.append(highlightStr)
}
if normalParts.count > 1 {
resultString.append(NSAttributedString(string: normalParts[1], attributes: [.font: Fonts.regular]))
}
return resultString
}
private enum Fonts {
static let regular = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .medium)
static let highlight = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular)
}
private enum Appearance {
static let iconOffset: CGFloat = 1.0
static let iconSize: CGFloat = 16.0
static var highlightColor: UIColor {
.invertedLabel
}
}
}
private extension NSAttributedString {
convenience init(format: NSAttributedString, args: NSAttributedString...) {
let mutableNSAttributedString = NSMutableAttributedString(attributedString: format)
args.forEach { (attributedString) in
let range = NSString(string: mutableNSAttributedString.string).range(of: "%@")
mutableNSAttributedString.replaceCharacters(in: range, with: attributedString)
}
self.init(attributedString: mutableNSAttributedString)
}
}
| gpl-2.0 | 7cd4de02ad210bd66c11fca0437247e1 | 59.747433 | 234 | 0.726034 | 4.694383 | false | false | false | false |
evertoncunha/EPCSpinnerView | EPCSpinnerView/Classes/EPCSpinnerView.swift | 1 | 2057 | //
// SpinnerView.swift
//
// Created by Everton on 24/08/17.
//
import UIKit
public protocol EPCSpinnerViewProtocol {
var iconSpinner: EPCDrawnIconSpinner { get }
var state: EPCSpinnerView.SpinnerState { get set }
func addIcon(_ view: UIView)
func startAnimating()
}
open class EPCSpinnerView: UIView, EPCSpinnerViewProtocol {
public enum SpinnerState: Int {
case loading
case error
case success
}
open let iconSpinner: EPCDrawnIconSpinner
open static let suggestedSize = CGSize(width: 180, height: 180)
required public init?(coder aDecoder: NSCoder) {
fatalError("\(#file) \(#function) not implemented")
}
override public init(frame: CGRect) {
var frame = frame
if frame.size.equalTo(CGSize.zero) {
frame.size = EPCSpinnerView.suggestedSize
}
var fraBounds = frame
fraBounds.origin = CGPoint.zero
iconSpinner = EPCDrawnIconSpinner(frame: fraBounds)
iconSpinner.autoresizingMask = [.flexibleWidth, .flexibleHeight]
super.init(frame: frame)
backgroundColor = UIColor.clear
clipsToBounds = true
layer.masksToBounds = true
contentMode = .redraw
addSubview(iconSpinner)
}
open var state: SpinnerState = .loading {
didSet {
switch state {
case .error:
iconSpinner.setError()
case .loading:
iconSpinner.state = .loading
iconSpinner.start()
case .success:
iconSpinner.setSuccess()
}
}
}
fileprivate func prop(_ val: CGFloat) -> CGFloat {
return (frame.size.height * val)/180
}
// MARK: - Open
open func addIcon(_ view: UIView) {
view.center = CGPoint(
x: CGFloat(Int(self.frame.size.width/2)),
y: CGFloat(Int(self.frame.size.height/2))
)
view.autoresizingMask = [
.flexibleTopMargin,
.flexibleRightMargin,
.flexibleLeftMargin,
.flexibleBottomMargin,
.flexibleWidth,
.flexibleHeight
]
insertSubview(view, at: 0)
}
open func startAnimating() {
iconSpinner.start()
}
}
| mit | 39c4d30d2ece087d6c8d0a8741ea9950 | 20.427083 | 68 | 0.656296 | 4.122244 | false | false | false | false |
Foild/SugarRecord | library/CoreData/Base/SugarRecordCDContext.swift | 1 | 7826 | //
// SugarRecordCDContext.swift
// SugarRecord
//
// Created by Pedro Piñera Buendía on 11/09/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import CoreData
public class SugarRecordCDContext: SugarRecordContext
{
/// NSManagedObjectContext context
let contextCD: NSManagedObjectContext
/**
SugarRecordCDContext initializer passing the CoreData context
- parameter context: NSManagedObjectContext linked to this SugarRecord context
- returns: Initialized SugarRecordCDContext
*/
init (context: NSManagedObjectContext)
{
self.contextCD = context
}
/**
Notifies the context that you're going to start an edition/removal/saving operation
*/
public func beginWriting()
{
// CD begin writing does nothing
}
/**
Notifies the context that you've finished an edition/removal/saving operation
*/
public func endWriting()
{
var error: NSError?
do {
try self.contextCD.save()
} catch let error1 as NSError {
error = error1
}
if error != nil {
let exception: NSException = NSException(name: "Database operations", reason: "Couldn't perform your changes in the context", userInfo: ["error": error!])
SugarRecord.handle(exception)
}
}
/**
* Asks the context for writing cancellation
*/
public func cancelWriting()
{
self.contextCD.rollback()
}
/**
Creates and object in the context (without saving)
- parameter objectClass: Class of the created object
- returns: The created object in the context
*/
public func createObject(objectClass: AnyClass) -> AnyObject?
{
let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type
let object: AnyObject = NSEntityDescription.insertNewObjectForEntityForName(managedObjectClass.modelName(), inManagedObjectContext: self.contextCD)
return object
}
/**
Insert an object in the context
- parameter object: NSManagedObject to be inserted in the context
*/
public func insertObject(object: AnyObject)
{
moveObject(object as! NSManagedObject, inContext: self.contextCD)
}
/**
Find NSManagedObject objects in the database using the passed finder
- parameter finder: SugarRecordFinder usded for querying (filtering/sorting)
- returns: Objects fetched
*/
public func find<T>(finder: SugarRecordFinder<T>) -> SugarRecordResults<T>
{
let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder)
var error: NSError?
var objects: [AnyObject]?
do {
objects = try self.contextCD.executeFetchRequest(fetchRequest)
} catch let error1 as NSError {
error = error1
objects = nil
}
SugarRecordLogger.logLevelInfo.log("Found \((objects == nil) ? 0 : objects!.count) objects in database")
if objects == nil {
return SugarRecordResults(coredataResults: [NSManagedObject](), finder: finder)
}
else {
return SugarRecordResults(coredataResults: objects as! [NSManagedObject], finder: finder)
}
}
/**
Returns the NSFetchRequest from a given Finder
- parameter finder: SugarRecord finder with the information about the filtering and sorting
- returns: Created NSFetchRequest
*/
public class func fetchRequest<T>(fromFinder finder: SugarRecordFinder<T>) -> NSFetchRequest
{
let objectClass: NSObject.Type = finder.objectClass!
let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName())
fetchRequest.predicate = finder.predicate
var sortDescriptors: [NSSortDescriptor] = finder.sortDescriptors
switch finder.elements {
case .first:
fetchRequest.fetchLimit = 1
case .last:
if !sortDescriptors.isEmpty{
sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending))
}
fetchRequest.fetchLimit = 1
case .firsts(let number):
fetchRequest.fetchLimit = number
case .lasts(let number):
if !sortDescriptors.isEmpty{
sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending))
}
fetchRequest.fetchLimit = number
case .all:
break
}
fetchRequest.sortDescriptors = sortDescriptors
return fetchRequest
}
/**
Deletes a given object
- parameter object: NSManagedObject to be deleted
- returns: If the object has been properly deleted
*/
public func deleteObject<T>(object: T) -> SugarRecordContext
{
let managedObject: NSManagedObject? = object as? NSManagedObject
let objectInContext: NSManagedObject? = moveObject(managedObject!, inContext: contextCD)
if objectInContext == nil {
let exception: NSException = NSException(name: "Database operations", reason: "Imposible to remove object \(object)", userInfo: nil)
SugarRecord.handle(exception)
}
SugarRecordLogger.logLevelInfo.log("Object removed from database")
self.contextCD.deleteObject(managedObject!)
return self
}
/**
Deletes NSManagedObject objecs from an array
- parameter objects: NSManagedObject objects to be dleeted
- returns: If the deletion has been successful
*/
public func deleteObjects<T>(objects: SugarRecordResults<T>) -> ()
{
var objectsDeleted: Int = 0
for (var index = 0; index < Int(objects.count) ; index++) {
let object: T! = objects[index]
if (object != nil) {
let _ = deleteObject(object)
}
}
SugarRecordLogger.logLevelInfo.log("Deleted \(objects.count) objects")
}
/**
* Count the number of entities of the given type
*/
public func count(objectClass: AnyClass, predicate: NSPredicate? = nil) -> Int
{
let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName())
fetchRequest.predicate = predicate
var error: NSError?
let count = self.contextCD.countForFetchRequest(fetchRequest, error: &error)
SugarRecordLogger.logLevelInfo.log("Found \(count) objects in database")
return count
}
//MARK: - HELPER METHODS
/**
Moves an NSManagedObject from one context to another
- parameter object: NSManagedObject to be moved
- parameter context: NSManagedObjectContext where the object is going to be moved to
- returns: NSManagedObject in the new context
*/
func moveObject(object: NSManagedObject, inContext context: NSManagedObjectContext) -> NSManagedObject?
{
do {
let objectInContext: NSManagedObject? = try context.existingObjectWithID(object.objectID)
return objectInContext
}
catch let error as NSError {
let exception: NSException = NSException(name: "Database operations", reason: "Couldn't move the object into the new context", userInfo: nil)
SugarRecord.handle(exception)
print(error.description)
return nil
}
}
} | mit | 5214853dca65a11d9196714d946de128 | 33.471366 | 166 | 0.646728 | 5.369938 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/extension/UIView+extension.swift | 1 | 1287 | //
// UIView+extension.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/10/20.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
extension UIView{
var x: CGFloat{
get{
return self.frame.origin.x
}
set{
self.frame.origin.x = newValue
}
}
var y: CGFloat{
get{
return self.frame.origin.y
}
set{
self.frame.origin.y = newValue
}
}
var width: CGFloat{
get{
return self.frame.size.width
}
set{
self.frame.size.width = newValue
}
}
var height: CGFloat{
get{
return self.frame.size.height
}
set{
self.frame.size.height = newValue
}
}
var centerX: CGFloat{
get{
return self.center.x
}
set{
self.center.x = newValue
}
}
var centerY: CGFloat{
get{
return self.center.y
}
set{
self.center.y = newValue
}
}
var size: CGSize{
get{
return self.frame.size
}
set{
self.frame.size = newValue
}
}
}
| apache-2.0 | b31bc9c53a738dbfc3333e169bec5599 | 16.534247 | 50 | 0.439844 | 4.155844 | false | false | false | false |
castial/Quick-Start-iOS | Quick-Start-iOS/Controllers/MainTabBarController.swift | 1 | 1651 | //
// MainTabBarController.swift
// Quick-Start-iOS
//
// Created by work on 2016/10/13.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
// MARK: - Class
class MainTabBarController: UITabBarController {
}
// MARK: - LifeCycle
extension MainTabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let homeVC: HomeViewController = HomeViewController()
let locationVC: LocationViewController = LocationViewController()
let meVC: MeViewController = MeViewController()
setupChildVC(vc: homeVC, title: "首页", imageName: "home", selectedImageName: "home_selected")
setupChildVC(vc: locationVC, title: "位置", imageName: "location", selectedImageName: "location_selected")
setupChildVC(vc: meVC, title: "我", imageName: "me", selectedImageName: "me_selected")
}
}
// MARK: - Private Methods
extension MainTabBarController {
fileprivate func setupChildVC(vc: UIViewController, title: NSString, imageName: NSString, selectedImageName: NSString) {
let nav: HYNavigationController = HYNavigationController ()
nav.vc = vc
nav.navTitle = title as String
nav.imageName = imageName as String
nav.selectedImageName = selectedImageName as String
addChildViewController(nav)
setupTabBarAttributes()
}
fileprivate func setupTabBarAttributes() {
UITabBar.appearance().tintColor = UIColor (red: 146/255, green: 185/255, blue: 74/255, alpha: 1.0)
// UITabBar.appearance().isTranslucent = false // 取消TabBar默认透明效果
}
}
| mit | 8312d864c3e4adb6121a7c716bd129f1 | 32.791667 | 124 | 0.676326 | 4.66092 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/More/MoreViewController.swift | 1 | 3485 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import UIKit
class MoreViewController: CustomWidthViewController {
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var newsLabel: UILabel!
@IBOutlet private weak var additionalMaterialsContainerHeight: NSLayoutConstraint!
@IBOutlet private weak var announcementsContainerHeight: NSLayoutConstraint!
private lazy var actionButton: UIBarButtonItem = {
let markAllAsReadActionTitle = NSLocalizedString("announcement.alert.mark all as read",
comment: "alert action title to mark all announcements as read")
let markAllAsReadAction = Action(title: markAllAsReadActionTitle, image: Action.Image.markAsRead) {
AnnouncementHelper.markAllAsVisited()
}
let item = UIBarButtonItem.circularItem(
with: R.image.navigationBarIcons.dots(),
target: self,
menuActions: [[markAllAsReadAction]]
)
item.accessibilityLabel = NSLocalizedString(
"accessibility-label.announcements.navigation-bar.item.actions",
comment: "Accessibility label for actions button in navigation bar of the course card view"
)
return item
}()
override func viewDidLoad() {
super.viewDidLoad()
let font = UIFont.boldSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .largeTitle).pointSize)
self.newsLabel.font = UIFontMetrics(forTextStyle: .largeTitle).scaledFont(for: font)
NotificationCenter.default.addObserver(self,
selector: #selector(updateUIAfterLoginStateChanged),
name: UserProfileHelper.loginStateDidChangeNotification,
object: nil)
self.updateUIAfterLoginStateChanged()
self.addRefreshControl()
self.refresh()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let tableViewController = segue.destination as? UITableViewController {
tableViewController.tableView.isScrollEnabled = false
} else if let collectionViewController = segue.destination as? UICollectionViewController {
collectionViewController.collectionView.isScrollEnabled = false
}
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
super.preferredContentSizeDidChange(forChildContentContainer: container)
if container is AdditionalLearningMaterialListViewController {
self.additionalMaterialsContainerHeight?.constant = container.preferredContentSize.height
} else if container is AnnouncementListViewController {
self.announcementsContainerHeight?.constant = container.preferredContentSize.height
}
}
@objc private func updateUIAfterLoginStateChanged() {
self.navigationItem.rightBarButtonItem = UserProfileHelper.shared.isLoggedIn ? self.actionButton : nil
}
}
extension MoreViewController: RefreshableViewController {
var refreshableScrollView: UIScrollView {
return self.scrollView
}
func refreshingAction() -> Future<Void, XikoloError> {
return AnnouncementHelper.syncAllAnnouncements().asVoid()
}
}
| gpl-3.0 | 4d144abf920529ed0f72ea1d29e151a2 | 38.590909 | 121 | 0.68915 | 6.090909 | false | false | false | false |
milseman/swift | stdlib/public/SDK/Foundation/NSStringAPI.swift | 6 | 74434 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
func _toNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound.encodedOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
}
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = ns as String
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = NSString(characters: utf16CodeUnits, length: count) as String
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag) as String
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = ns as String
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns as String
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns as String
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = ns as String
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = ns as String
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = s as String
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString as NSString
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(encodedOffset: utf16Index)
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(
range ?? startIndex..<endIndex
),
locale: locale
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;
/// The smallest encoding to which the string can be converted without
/// loss of information.
public var smallestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.smallestEncoding)
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string created by replacing all characters in the string
/// not in the specified set with percent encoded characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string created by appending a string constructed from a given
/// format string and the following arguments.
public func appendingFormat<
T : StringProtocol
>(
_ format: T, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format._ephemeralString, arguments: arguments))
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string created by appending the given string.
// FIXME(strings): shouldn't it be deprecated in favor of `+`?
public func appending<
T : StringProtocol
>(_ aString: T) -> String {
return _ns.appending(aString._ephemeralString)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: String.CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding<
T : StringProtocol
>(
toLength newLength: Int,
withPad padString: T,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength,
withPad: padString._ephemeralString,
startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// A new string made from the string by replacing all percent encoded
/// sequences with the matching UTF-8 characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters<
T : StringProtocol, R : RangeExpression
>(in range: R, with replacement: T) -> String where R.Bound == Index {
return _ns.replacingCharacters(
in: _toNSRange(range.relative(to: self)),
with: replacement._ephemeralString)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the string are replaced by
/// another given string.
public func replacingOccurrences<
Target : StringProtocol,
Replacement : StringProtocol
>(
of target: Target,
with replacement: Replacement,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
let target = target._ephemeralString
let replacement = replacement._ephemeralString
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toNSRange(
searchRange ?? startIndex..<endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write<
T : StringProtocol
>(
toFile path: T, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
toFile: path._ephemeralString,
atomically: useAuxiliaryFile,
encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
/// Perform string transliteration.
@available(OSX 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) where R.Bound == Index {
let range = range.relative(to: self)
_ns.enumerateLinguisticTags(
in: _toNSRange(range),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the specified range of
/// the string.
///
/// Mutation of a string value while enumerating its substrings is not
/// supported. If you need to mutate a string from within `body`, convert
/// your string to an `NSMutableString` instance and then call the
/// `enumerateSubstrings(in:options:using:)` method.
///
/// - Parameters:
/// - range: The range within the string to enumerate substrings.
/// - opts: Options specifying types of substrings and enumeration styles.
/// If `opts` is omitted or empty, `body` is called a single time with
/// the range of the string specified by `range`.
/// - body: The closure executed for each substring in the enumeration. The
/// closure takes four arguments:
/// - The enumerated substring. If `substringNotRequired` is included in
/// `opts`, this parameter is `nil` for every execution of the
/// closure.
/// - The range of the enumerated substring in the string that
/// `enumerate(in:options:_:)` was called on.
/// - The range that includes the substring as well as any separator or
/// filler characters that follow. For instance, for lines,
/// `enclosingRange` contains the line terminators. The enclosing
/// range for the first string enumerated also contains any characters
/// that occur before the string. Consecutive enclosing ranges are
/// guaranteed not to overlap, and every single character in the
/// enumerated range is included in one and only one enclosing range.
/// - An `inout` Boolean value that the closure can use to stop the
/// enumeration by setting `stop = true`.
public func enumerateSubstrings<
R : RangeExpression
>(
in range: R,
options opts: String.EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) where R.Bound == Index {
_ns.enumerateSubstrings(
in: _toNSRange(range.relative(to: self)), options: opts) {
var stop_ = false
body($0,
self._range($1),
self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes<
R : RangeExpression
>(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: R,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool where R.Bound == Index {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: Swift.min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toNSRange(range.relative(to: self)),
remaining: $0)
}
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range.relative(to: self)))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range.relative(to: self)))
}
}
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(_ns.lineRange(for: _toNSRange(aRange.relative(to: self))))
}
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] where R.Bound == Index {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toNSRange(range.relative(to: self)),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography,
tokenRanges: $0) as NSArray
}
if nsTokenRanges != nil {
tokenRanges?.pointee = (nsTokenRanges! as [AnyObject]).map {
self._range($0.rangeValue)
}
}
return result as! [String]
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(
_ns.paragraphRange(for: _toNSRange(aRange.relative(to: self))))
}
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toNSRange(
aRange ?? startIndex..<endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences<
R : RangeExpression
>(
for range: R
) -> Range<Index> where R.Bound == Index {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(
for: _toNSRange(range.relative(to: self))))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range<
T : StringProtocol
>(
of aString: T,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
let aString = aString._ephemeralString
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toNSRange(
searchRange ?? startIndex..<endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRange<
T : StringProtocol
>(of string: T) -> Range<Index>? {
return _optionalRange(
_ns.localizedStandardRange(of: string._ephemeralString))
}
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains<T : StringProtocol>(_ other: T) -> Bool {
let r = self.range(of: other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.contains(other._ephemeralString))
}
return r
}
/// Returns a Boolean value indicating whether the given string is non-empty
/// and contained within this string by case-insensitive, non-literal
/// search, taking into account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs, can be
/// achieved by calling `range(of:options:range:locale:)`.
///
/// Equivalent to:
///
/// range(of: other, options: .caseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains<
T : StringProtocol
>(_ other: T) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r ==
_ns.localizedCaseInsensitiveContains(other._ephemeralString))
}
return r
}
}
// Deprecated slicing
extension StringProtocol where Index == String.Index {
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range from' operator.")
public func substring(from index: Index) -> String {
return _ns.substring(from: index.encodedOffset)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range upto' operator.")
public func substring(to index: Index) -> String {
return _ns.substring(to: index.encodedOffset)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript.")
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toNSRange(aRange))
}
}
extension StringProtocol {
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
fatalError("unavailable function can't be called")
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
fatalError("unavailable function can't be called")
}
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
fatalError("unavailable function can't be called")
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
fatalError("unavailable function can't be called")
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
fatalError("unavailable function can't be called")
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: String.CompareOptions = [], locale: Locale?
) -> String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
fatalError("unavailable property")
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
fatalError("unavailable function can't be called")
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: String.Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
fatalError("unavailable function can't be called")
}
}
extension StringProtocol {
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: String.CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: String.EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | a35f2d0a98f0e3248e3ea5e14b2e0d9e | 34.35962 | 279 | 0.674038 | 4.771894 | false | false | false | false |
tristanchu/FlavorFinder | FlavorFinder/FlavorFinder/HotpotSubviewController.swift | 1 | 4371 |
// HotpotSubviewController.swift
// FlavorFinder
//
// Created by Jaki Kimball on 1/31/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
// Hotpot, a.k.a. where search terms are displayed and can be interacted with.
//
import Foundation
import UIKit
import Parse
import MGSwipeTableCell
import DZNEmptyDataSet
import DOFavoriteButton
import Darwin
import ASHorizontalScrollView
class HotpotSubviewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {
// class constants
let CELL_IDENTIFIER = "hotpotCell"
let CELL_HEIGHT : CGFloat = 20
let EDGE_INSET = 10
let ITEM_WIDTH : CGFloat = 100
let FRAME_WIDTH : CGFloat = 200 // debug: arbitrary for now
let HOTPOT_COLOR = NAVI_COLOR
let CELL_LABEL_FONT = UIFont(name: "Avenir Next Medium", size: 17)
let CELL_X_POS : CGFloat = 3
let CELL_Y_POS : CGFloat = -3
let CELL_LABEL_COLOR = UIColor.whiteColor()
let REMOVE_BTN_FONT = UIFont.fontAwesomeOfSize(20)
let CELL_BKGD_COLOR = NAVI_LIGHT_COLOR
let REMOVE_BTN_TEXT = String.fontAwesomeIconWithName(.Remove)
// SETUP FUNCTIONS
override func viewDidLoad() {
super.viewDidLoad()
if collectionView == nil {
print("ERROR: Hotpot collection view is nil!")
}
collectionView?.backgroundColor = HOTPOT_COLOR
collectionView?.reloadData()
}
// CUSTOM FUNCTIONS
func addHotpotIngredient(ingredient: PFIngredient) {
currentSearch.append(ingredient)
collectionView?.reloadData()
}
func removeHotpotIngredientClicked(sender: RemoveHotpotIngredientButton) {
if currentSearch.isEmpty {
print("ERROR: Tried to remove hotpot ingredient when search is empty.")
return
}
currentSearch.removeAtIndex(currentSearch.indexOf(sender.ingredient as! PFIngredient)!)
// Let parent know that hotpot ingredient was removed
if let parent = parentViewController as! SearchResultsViewController? {
parent.hotpotIngredientWasRemoved()
}
collectionView?.reloadData()
}
// COLLECTION FUNCTIONS
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return currentSearch.count
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CELL_IDENTIFIER, forIndexPath: indexPath) as! HotpotCollectionViewCell
let ingredient = currentSearch[indexPath.section]
let name : NSString = ingredient[_s_name] as! NSString
let size : CGSize = name.sizeWithAttributes([NSFontAttributeName: UIFont.fontAwesomeOfSize(25)])
cell.nameLabel.frame = CGRectMake(CELL_X_POS, CELL_Y_POS, size.width, size.height)
cell.nameLabel.text = ingredient[_s_name] as? String
cell.nameLabel.font = CELL_LABEL_FONT
cell.nameLabel.textColor = CELL_LABEL_COLOR
cell.addSubview(cell.nameLabel)
cell.removeBtn.frame = CGRectMake(cell.frame.width - 25, 0, 20, 20)
cell.removeBtn.titleLabel?.font = REMOVE_BTN_FONT
cell.removeBtn.setTitle(REMOVE_BTN_TEXT, forState: .Normal)
cell.removeBtn.tintColor = NAVI_BUTTON_COLOR
cell.removeBtn.addTarget(self, action: Selector("removeHotpotIngredientClicked:"), forControlEvents: UIControlEvents.TouchUpInside)
cell.removeBtn.ingredient = ingredient
cell.addSubview(cell.removeBtn)
cell.backgroundColor = CELL_BKGD_COLOR
cell.layer.cornerRadius = 5
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let ingredient : PFObject = currentSearch[indexPath.section]
let name : NSString = ingredient[_s_name] as! NSString
var size : CGSize = name.sizeWithAttributes([NSFontAttributeName: UIFont.fontAwesomeOfSize(20)])
size.width += 25
return size
}
} | mit | ef508c81970199750dfe4352e395f9af | 36.681034 | 169 | 0.693364 | 4.921171 | false | false | false | false |
luckychunxiao/HockeySDK-iOSDemo-Swift | Classes/BITFeedbackViewController.swift | 2 | 4768 | //
// BITFeedbackViewController.swift
// HockeySDK-iOSDemo-Swift
//
// Created by Kevin Li on 18/10/2016.
//
import UIKit
class BITFeedbackViewController: UITableViewController {
// MARK: - Private
func openShareActivity() {
let feedbackActivity = BITFeedbackActivity.init()
feedbackActivity.customActivityTitle = "Feedback"
var activityViewController:UIActivityViewController? = UIActivityViewController.init(activityItems: ["Share this text"],applicationActivities: [feedbackActivity])
activityViewController?.excludedActivityTypes = [.assignToContact]
self.present(activityViewController!, animated: true) {
activityViewController?.excludedActivityTypes = nil
activityViewController = nil
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 4
}
return 1
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return NSLocalizedString("View Controllers", comment: "")
} else {
return NSLocalizedString("Alerts", comment: "")
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 || section == 2 {
return NSLocalizedString("Presented UI relevant for localization", comment: "")
}
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
// Configure the cell...
if indexPath.section == 0 {
if indexPath.row == 0 {
cell!.textLabel?.text = NSLocalizedString("Modal presentation", comment: "")
} else if indexPath.row == 1 {
cell!.textLabel?.text = NSLocalizedString("Compose feedback", comment: "")
} else if indexPath.row == 2 {
cell!.textLabel?.text = NSLocalizedString("Compose with screenshot", comment: "")
} else {
cell!.textLabel?.text = NSLocalizedString("Compose with data", comment: "")
}
} else if indexPath.section == 1 {
cell!.textLabel?.text = NSLocalizedString("Activity/Share", comment: "")
} else {
cell!.textLabel?.text = NSLocalizedString("New feedback available", comment: "")
}
return cell!
}
//MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
let feedbackManager = BITHockeyManager.shared().feedbackManager
if indexPath.row == 0 {
feedbackManager.showFeedbackListView()
} else if indexPath.row == 1 {
feedbackManager.showFeedbackComposeView()
} else if indexPath.row == 2 {
feedbackManager.showFeedbackComposeViewWithGeneratedScreenshot()
} else {
let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let settingsDir = "\(path)/\(BITHOCKEY_IDENTIFIER)/BITFeedbackManager.plist"
let binaryData = NSData(contentsOfFile: settingsDir)
feedbackManager.showFeedbackComposeView(withPreparedItems: [binaryData!])
}
} else if indexPath.section == 1 {
openShareActivity()
} else {
let alert = UIAlertController(title: BITHockeyLocalizedString("HockeyFeedbackNewMessageTitle"), message: BITHockeyLocalizedString("HockeyFeedbackNewMessageText"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("HockeyFeedbackIgnore"), style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("HockeyFeedbackShow"), style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
| mit | b1627a8a2ad44c4f44bde7d276014538 | 39.752137 | 198 | 0.630663 | 5.563594 | false | false | false | false |
kaishin/learn-swift | swift/2014-07-20-dictionaries.swift | 2 | 601 | var routeOneEncounterRates = ["Pidgey": 0.55, "Rattata": 0.45]
var fishingEncounterRates: [String: Double] = [:]
fishingEncounterRates = [String: Double]()
// routeOneEncounterRates = ["Pidgey": "55%"]
routeOneEncounterRates.count
routeOneEncounterRates.isEmpty
let rattataRate = routeOneEncounterRates["Rattata"]
fishingEncounterRates["Poliwag"] = 0.5
routeOneEncounterRates["Mewtwo"] = 0.0
let pokéMart = ["Poké Ball": 200, "Potion": 300]
// pokéMart["Antidote"] = 100
routeOneEncounterRates["Mewtwo"] = nil
let comparison = ["Rattata": 0.45, "Pidgey": 0.55] == ["Pidgey": 0.55, "Rattata": 0.45]
| mit | f70db087338fc255d7a79bdb4f48d364 | 45 | 87 | 0.725753 | 3.114583 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.