Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

swift - Cannot fix "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

i have three vars so it seems occur compiler, when i try to check does time has passed or not. I have

let currentDate = Int(Date().timeIntervalSince1970)
let loginUpdateDate = sessionStore.userSession?.loginUpdateDate
let nextDateLoginUpdate = currentDate - loginUpdateDate

but when i try to do this, i'm getting

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

It simple operation with Int but seems it overloading for the compiler. Im doing this to use if statements later

if nextDateLoginUpdate < 300

full code is:

struct editProfileView: View {
    @State var loadImage : Image? = nil
    @State var source : UIImagePickerController.SourceType = .photoLibrary
    @EnvironmentObject var sessionStore : SessionStore
    @State var name: String = ""
    @State var bio:String = ""
    @Binding var showEditProfile:Bool
    @State var showEditPassword = false
    //    var user = User?
    @State var loadingView = false
    
    //image picker
    @State var showChoose = false
    @State var image: Image? = nil
    @State var showImagePicker = false
    @State var imageData : Data? = nil
    @State private var offsetValue: CGFloat = 0.0
    var body: some View {

            ZStack {
                VStack {
                    //переменные для даты и проверки последующего обновления данных на странице
                    //let loginUpdateDate = sessionStore.userSession?.loginUpdateDate
                    //let nextDateLoginUpdate = currentDate - loginUpdateDate
                    Group {
                        Group {
                            VStack {
                                    Group {
                                        //аватарка
                                        //если картинка не выбрана
                                        if (self.image == nil) {
                                            if (self.sessionStore.userSession?.profileImageUrl == nil) {
                                                ZStack(alignment: .bottomLeading) {
                                                    Image("user-placeholder")
                                                        .resizable()
                                                        .scaledToFill()
                                                        .clipShape(Circle())
                                                        .frame(width: 100, height: 100)
                                                    
                                                    Image(systemName: "goforward.plus").padding(5)
                                                }.frame(width: 100, height: 100)
                                                    .onTapGesture {
                                                        //выключаем если прошло меньше времени
                                                        self.showImagePicker = true
                                                }
                                            } else {
                                                if (self.loadImage == nil) {
                                                    ZStack(alignment: .bottomLeading) {
                                                        Image("user-placeholder")
                                                            .resizable()
                                                            .aspectRatio(contentMode: .fill)
                                                            .clipShape(Circle())
                                                            .frame(width: 100, height: 100)
                                                        
                                                        Image(systemName: "goforward.plus").padding(5)
                                                    }.frame(width: 100, height: 100)
                                                        .onTapGesture {
                                                            self.showChoose = true
                                                            //выключаем если прошло меньше времени
                                                    }
                                                }
                                                    
                                                else {
                                                    ZStack(alignment: .bottomLeading) {
                                                        loadImage!
                                                            .resizable()
                                                            .scaledToFill()
                                                            .clipShape(Circle())
                                                            .frame(width: 100, height: 100)
                                                        
                                                        Image(systemName: "goforward.plus").padding(5)
                                                    }.frame(width: 100, height: 100)
                                                        .onTapGesture {
                                                            self.showChoose = true
                                                            //выключаем если прошло меньше времени
                                                    }
                                                }
                                                
                                            }
                                            
                                            VStack(alignment: .center) {
                                                Text(name).font(.headline)
                                            }
                                            
                                            //если картинка выбрана
                                        } else {
                                            ZStack(alignment: .bottomLeading) {
                                                image! //может использовать "!" так как делаем проверку и уверены, что это не nil
                                                    .resizable()
                                                    .scaledToFill()
                                                    .clipShape(Circle())
                                                
                                                Image(systemName: "goforward.plus").padding(5)
                                            }.frame(width: 100, height: 100)
                                                .onTapGesture {
                                                    //                                self.showImagePicker = true
                                                    self.showChoose = true
                                            }
                                        }
                                        
                                        HStack {
                                            Text(LocalizedStringKey("Bio:")).fontWeight(.bold)
                                            Spacer()
                                        }
                                        HStack {
                                            TextField(LocalizedStringKey("Bio"), text:$bio).padding(.top)
                                        }.padding(.bottom).padding(.horizontal).background(Color("textFieldBackground")).cornerRadius(10)
                                    }
                            }
                        }.padding(.horizontal).padding(.top)
                            
                        Button(action: {
                            let currentUser = Auth.auth().currentUser
                            if (currentUser != nil) {
                                self.loadingView = true
                                let id = currentUser!.uid
//                                добавить в коллекцию ниже параметры когда получитсвя везде обновлять инфо
//                                "username" : self.name, "keywords" : self.name.splitStringToArray()
                                Ref.FIRESTORE_COLLECTION_USERS.document(id).updateData(["bio" : self.bio]) { (err) in
                                    //Конструкция: если err (ошибка) не nil, значит ест ьошибка и что-то пошло не так
                                    // если nil, значит все хорошо
                                    if let err = err {
                                        //делаем что-то если ошибка
                                        //например показываем надпись с сообщением об ошибке
                                        print("Error updating document: (err)")
                                        self.loadingView = false
                                    } else {
                                        self.sessionStore.userSession?.bio = self.bio
                                        //то же самое только если все получилось
                                        print("Document successfully updated")
                                        if (self.imageData == nil) {
                                            self.loadingView = false
                                            self.showEditProfile = false
                                        }
                                    }
                                }
                                
                                //save image
                                //Если новая картинка выбрана
                                if (self.imageData != nil && self.sessionStore.userSession != nil) {
                                    //Сначала загружаем в хранилище, а затем ссылку на это фото обновляем в базе данных у пользователя
                                    let storageAvatarUserId = Ref.STORAGE_AVATAR_USERID(userId: Auth.auth().currentUser!.uid)
                                    let metadata = StorageMetadata()
                                    metadata.contentType = "image/jpg"
                                    //для био было
                                    //cлушатель для обновления био
                                    self.sessionStore.userSession?.bio = self.bio
                                    //для логина - апдейт
                                    self.sessionStore.userSession?.username = self.name
                                    
                                    NotificationCenter.default.post(name: NSNotification.Name("update_profile_bio"), object: nil)
                                    StorageService.updateAvatar(userId: self.sessionStore.userSession!.uid, username: self.sessionStore.userSession!.username, email: self.sessionStore.userSession!.email, imageData: self.imageData!, metaData: metadata, storageAvatarRef: storageAvatarUserId, onSuccses: {url in
                                        if url != nil {
                                            self.sessionStore.userSession?.profileImageUrl = url!
                                            NotificationCenter.default.post(name: NSNotification.Name("update_profile_image"), object: nil)
                                            self.loadingView = false
                                            self.showEditProfile = false
                                            
                                        } else {
                                            self.loadingView = false
             

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think it is better to change the first line like the below snippet code:

let date = Date()
let timeInterval = date.timeIntervalSince1970
let currentDate = Int(timeInterval)

Test this I hope it helps otherwise you have to make the other code to smaller snippet


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...